Using same onClick listener with more than one vie

2019-07-19 15:12发布

问题:

I am using the same onClick listener for a number of items.

When I click I want to know which one.

I know that I can do a Switch statement on the getId() but would rather be able to get at the name of the item. Is there any easy way to do this?

回答1:

I think what you are referring to when you say "get the name" is the id string from resources. So you would have a switch statement like:

switch(view.getId()) {
    case R.id.HomeButtonOne:
        // Do Button One Action
        break;
    case R.id.HomeButtonTwo:
        // Do Button Two Action
        break;
}

otherwise please elaborate more on what you are trying to achieve.



回答2:

You have a few options.

  1. You could extend View with a class which you create and includes additional identifiable information. Then in onClick, cast the View to your class type.

  2. You could use an Adapter to better manager your views. This works best if you are displaying views of data instead of inert layouts or Drawables.

It's going to boil down to what you want to store and what you are viewing.



回答3:

Just make a class which implements OnClickListner and set an instance to your views:

class MyListener implements OnClickListener() {
 // ...
}

MyListener listener = new MyListener();

View view = (View) findViewById(R.id.myViewId);
view.setOnClickListener(listener);
view = (View) findViewById(R.id.myAnotherViewId);
view.setOnClickListener(listener);

...