Question

J'ai un problème ... J'ai différentes textviews avec un auditeur. Comme ceux-ci:

    help_modul.setOnClickListener(this);
    help_timetable.setOnClickListener(this);
    help_credits.setOnClickListener(this);
    help_todo.setOnClickListener(this);

Voici mon auditeur:

@Override
public void onClick(View v) {

 String temp=   v.getId(); // DOESNT WORK
 Toast.makeText(this, temp, Toast.LENGTH_LONG).show();

}

Dans mon écoute, je veux différer entre mon textview .... Par exemple Cliquez sur Textfield « a » faire, si un clic sur un autre textfield faire une autre opération ..

u ont des suggestions?

Était-ce utile?

La solution

Essayez quelque chose comme ceci:

@Override
public void onClick(View v) {

switch (v.getId()) {
      case R.id.textview1:
        doSomething1();
        break;
      case R.id.textview2
        doSomething2();
        break;
  }
}

Autres conseils

Vous pourriez a) make InstanceListeners tels que:

TextView(context).setOnClickListener(new OnClickListener() {
    @Override public void onClick(View view) {
        // ...
        Log.d(TAG, "I'm doing stuff");
    }
}

ou vous pouvez b) vérifier les instances de votre textview:

@Override public void onClick(View view) {
    if (view == mGirlTextView) {
        // Do Stuff
        Log.d(TAG, "I'm Forever alone");
    } else if (view == mBoyTextView) {
        // Do moar stuff
        Log.d(TAG, "Let's grab a beer");
    }
}

Utilisation d'un boîtier de commutateur

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.help_modul:
        // do code
        break;
    case R.id.help_timetable:
        // do code
        break;
    case R.id.help_credits:
        // do code
        break;
    case R.id.help_todo:
        // do code
        break;
    }

}

Dans cette déclaration String temp= v.getId(); // DOESNT WORK vous obtenez l'ID de vue qui est de type de données long puis attribuer à la variable String, qui peut être correct, mais il est mauvaise approche.

Utilisez ce code améliorée instread :

 @Override
 public void onClick(View v) {
    if(v.getId() == help_modul.getId())
    {
        /*do some work on the click*/
    }
    else if(v.getId() == help_timetable.getId())
    {
        /*do some work on the click*/
    }
    else if(v.getId() == help_credits.getId())
    {
        /*do some work on the click*/
    }
    else if(v.getId() == help_todo.getId())
    {
        /*do some work on the click*/
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top