开发者

Using same onClick listener with more than one view

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

Whe开发者_如何学Gon 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?


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.


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.


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

...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜