Android 多按钮监听器设置

转载自:http://my.oschina.net/laiwanshan/blog/99720


刚开始学习安卓的时候,设置监听多个按钮,我开了多个监听器,定义了多个onClick()函数,后来发现没必要。

有更简单的方法:


package com.example.dialogtest;
 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
public class MainDialogActivity extends Activity {
 
    private Button b1,b2,b3,b4,b5;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_dialog);
     
        b1=(Button)findViewById(R.id.button1);
        b2=(Button)findViewById(R.id.button2);
        b3=(Button)findViewById(R.id.button3);
        b4=(Button)findViewById(R.id.button4);
        b5=(Button)findViewById(R.id.button5);
   
        b1.setOnClickListener(new ButtonListener());
        b2.setOnClickListener(new ButtonListener());
        b3.setOnClickListener(new ButtonListener());
        b4.setOnClickListener(new ButtonListener());
        b5.setOnClickListener(new ButtonListener());
 
    }
 
    private class ButtonListener implements OnClickListener{
 
        public void onClick(View v) {
            switch(v.getId()){
            case R.id.button1:
                    ……
                    break;
            case R.id.button2:                  
                ……
                break;
                default:
                break;
            }
        }
         
    }
     
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main_dialog, menu);
        return true;
    }
}

你可能感兴趣的:(Android)