Using same onClick listener with more than one vie

2019-07-19 15:11发布

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?

3条回答
Juvenile、少年°
2楼-- · 2019-07-19 15:50

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楼-- · 2019-07-19 15:57

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);

...
查看更多
成全新的幸福
4楼-- · 2019-07-19 16:01

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.

查看更多
登录 后发表回答