开发者

OnClick listener - one function for all clicks

In my layout xml file I have set the android:onClick attribute for a Button element to a function in my activity. So when I click the button the function is called with a Vi开发者_StackOverflowew as its argument. Are there any information in that View argument that has the id of the button being clicked? I'm trying to figure out if I have to have one onClick function for every element or if I can use one function and switch depending on the id of the element being clicked.


switch (v.getID) { 
case R.id.A:
 .....
}


ohh Apps has the answer all right... just for throughness I have something like so... case sensitive stuff.... funny how a getID won't work while a getId will be golden... funny how a compiler couldn't do a "sloppy check" and correct such case issues.

like so

View myButton = findViewById(R.id.mybutton);
     myButton.setOnClickListener(this); 
  View myOtherButton = findViewById(R.id.myotherbutton);
       myOtherButton.setOnClickListener(this); 
public void onClick(View v) {
             switch (v.getId()) {
           case R.id.mybutton:  
                              //Do something related to the mybutton click

            break;
        case R.id.myotherbutton:    
                              //Do something related to the myotherbutton click

            break;
       //chain all Resource ID's here like above.... 
                                   }
}

you must also not to forget to setup a Onclick listener for every click event before the switch or the case will never get resolved....

//whoo hoo. 8cupsaday android app coming soon!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜