Variable OnClick Listener Android

此生再无相见时 提交于 2019-12-22 08:06:11

问题


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.


回答1:


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



回答2:


If you are using 1.6+ version of the SDK you can use android:onClick to set the onClick handler of a view. In your activity you must have a method with the following signature. The view is the view that was clicked.

void onClick(View v) {
    switch(v.getId()) {
        case R.id.button1:
            //do something fantastic;
            break;
    }
}



回答3:


public class MainActivity extends Activity implements View.OnClickListener{

btnXXX.setOnClickListener(this);

public void onClick(View v) {
    if (v.getId()==R.id.btnXXX){
        dialog.show();
    } else {
        handleOtherViews(v);
    }
}



回答4:


Alternatively, you can specify the method to call in xml:

<Button android:id="@id/button" android:text="@string/button" android:onClick="someMethod" />


来源:https://stackoverflow.com/questions/3120544/variable-onclick-listener-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!