在设置了多个按钮之后如何分辨你点击了哪个按钮呢?不多说直接上代码,通过v.getId()来得到你点击的按钮的id,然后通过switch()便可以处理:
1 package com.example.multiButtons; 2 3 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.view.Menu; 7 import android.view.MenuItem; 8 import android.view.View; 9 import android.view.View.OnClickListener; 10 import android.widget.Button; 11 import android.widget.Toast; 12 13 public class MainActivity extends Activity implements OnClickListener{ 14 15 @Override 16 protected void onCreate(Bundle savedInstanceState) { 17 super.onCreate(savedInstanceState); 18 setContentView(R.layout.activity_main); 19 Button btn1 = findViewById(R.id.btn1); 20 btn1.setOnClickListener(this); 21 Button btn2 = findViewById(R.id.btn2); 22 btn2.setOnClickListener(this); 23 Button btn3 = findViewById(R.id.btn3); 24 btn3.setOnClickListener(this); 25 Button btn4 = findViewById(R.id.btn4); 26 btn4.setOnClickListener(this); 27 Button btn5 = findViewById(R.id.btn5); 28 btn5.setOnClickListener(this); 29 } 30 31 @Override 32 public boolean onCreateOptionsMenu(Menu menu) { 33 // Inflate the menu; this adds items to the action bar if it is present. 34 getMenuInflater().inflate(R.menu.main, menu); 35 return true; 36 } 37 38 @Override 39 public boolean onOptionsItemSelected(MenuItem item) { 40 // Handle action bar item clicks here. The action bar will 41 // automatically handle clicks on the Home/Up button, so long 42 // as you specify a parent activity in AndroidManifest.xml. 43 int id = item.getItemId(); 44 if (id == R.id.action_settings) { 45 return true; 46 } 47 return super.onOptionsItemSelected(item); 48 } 49 50 @Override 51 public void onClick(View v) { 52 // TODO Auto-generated method stub 53 switch(v.getId()) { 54 case R.id.btn1:{ 55 Toast.makeText(MainActivity.this, "您点击了按钮1", Toast.LENGTH_SHORT).show();break; 56 } 57 case R.id.btn2:{ 58 Toast.makeText(MainActivity.this, "您点击了按钮2", Toast.LENGTH_SHORT).show();break; 59 } 60 case R.id.btn3:{ 61 Toast.makeText(MainActivity.this, "您点击了按钮3", Toast.LENGTH_SHORT).show();break; 62 } 63 case R.id.btn4:{ 64 Toast.makeText(MainActivity.this, "您点击了按钮4", Toast.LENGTH_SHORT).show();break; 65 } 66 case R.id.btn5:{ 67 Toast.makeText(MainActivity.this, "您点击了按钮5", Toast.LENGTH_SHORT).show();break; 68 } 69 70 } 71 } 72 }
效果展示: