有没有办法有1利斯特的onClick许多按钮在那里我能折腾一个case语句的基础上被点击了什么按钮做的事情。
我知道我可以做100种不同的听众为100按钮,但我觉得我可以创造一些漂亮的变量来做到这一点在code少行。
解决方案 按钮BTN1,BTN2;公共无效的onCreate(包B){ //在这里做正常的事情像分配 //内容视图到活动中,启动按钮等 //那么你分配相同的监听器,两个按钮 btn1.setOnClickListener(yourListener); btn2.setOnClickListener(yourListener);}//声明一个OnClickListener将执行不同的操作//取决于被点击的看法View.OnClickListener yourListener =新View.OnClickListener(){ 公共无效的onClick(视图v){ 如果(V == BTN1){ // 做一点事 } ELSEIF(V == BTN1){ //做另一件事 } }};
Is there a way to have 1 onClick Lister for many buttons where I can toss a case statement to do things based on what buttons were clicked.
I know I can make 100 different listeners for 100 buttons but I have to think I can create some nifty variables to do it in less lines of code.
解决方案Button btn1, btn2;
public void onCreate(Bundle b)
{
// here you do normal things like assigning a
// content view to the activity, initiate buttons, etc.
// then you assign the same listener to both buttons
btn1.setOnClickListener(yourListener);
btn2.setOnClickListener(yourListener);
}
// declare a OnClickListener that will execute different actions
// depending on the view that was clicked
View.OnClickListener yourListener = new View.OnClickListener(){
public void onClick (View v){
if( v == btn1 ){
// do something
}
elseif( v == btn1 ){
// do another thing
}
}
};