定义按钮监听事件的方法汇总

 
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />



    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="OK1" />


    <Button
        android:id="@+id/button2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="OK2" />
    
    <Button
        android:id="@+id/button3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="OK3" />

</LinearLayout>
Activity
package com.binni.AndroidTest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidTestActivity extends Activity implements OnClickListener {
    private Button button01;
    private Button button02;
    private Button button03;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button01=(Button)findViewById(R.id.button1);
        button02=(Button)findViewById(R.id.button2);
        button03=(Button)findViewById(R.id.button3);
        button01.setOnClickListener(new OnClickListener() {
            
            public void onClick(View v) {
                // TODO Auto-generated method stub
                ToastDisplay("OK1 Button Clicked....");
            }
        });
        
        button02.setOnClickListener(new btnClicklsner());
        button03.setOnClickListener(this);
    }
    
    void ToastDisplay(String str)
    {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }
    
    class btnClicklsner implements OnClickListener {
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ToastDisplay("OK2 Button Clicked....");
        }
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        ToastDisplay(((Button)v).getText() + " Button Clicked....");
    }
}
原文地址:https://www.cnblogs.com/nikyxxx/p/2547799.html