i have a problem... I have different textviews with a listener. Like these ones:

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

Here is my listener:

@Override
public void onClick(View v) {

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

}

In my listener I want to differ between my textview.... For example Click on Textfield "a "do that, if a click on another textfield do another operation..

Have u any suggestions?

有帮助吗?

解决方案

Try something like this:

@Override
public void onClick(View v) {

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

其他提示

You could a) make InstanceListeners such as:

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

or you could b) check the instances of your 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");
    }
}

Use a switch case

@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;
    }

}

In this statement String temp= v.getId(); // DOESNT WORK you are getting the id of view which is of datatype long and then assigning to the String variable, which may be correct but it is bad approach.

Use this improved code 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*/
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top