首页 > 代码库 > 页面上有多个Button的代码

页面上有多个Button的代码

当页面上有多个按钮,为每个都写个响应函数相当麻烦:可以这样来做:

方法1:

 1 public class Sudoku extends Activity implements OnClickListener{ 2     /** Called when the activity is first created. */ 3     @Override 4     public void onCreate(Bundle savedInstanceState) { 5         setContentView(R.layout.main); 6      super.onCreate(savedInstanceState);       7                 8         View continueButton=this.findViewById(R.id.continue_button); 9         continueButton.setOnClickListener(this);10         View newButton =this.findViewById(R.id.new_button);11         newButton.setOnClickListener(this);12         View aboutButton=this.findViewById(R.id.about_button);13         aboutButton.setOnClickListener(this);14         View exitButton=this.findViewById(R.id.exit_button);15         exitButton.setOnClickListener(this);16               17     }  18     public void onClick(View v)19     {20      switch(v.getId()){21      case R.id.about_button:22       Intent i=new Intent(this,About.class);23       startActivity(i);

 

方法2:

 1 public class IntentSelectActivity extends Activity implements View.OnClickListener{   2     /** Called when the activity is first created. */   3     @Override   4     public void onCreate(Bundle savedInstanceState) {   5         super.onCreate(savedInstanceState);   6         setContentView(R.layout.main);   7            8         Button button1 = (Button)findViewById(R.id.btn1);   9         Button button2 = (Button)findViewById(R.id.btn2);  10         Button button3 = (Button)findViewById(R.id.btn3);  11         button1.setOnClickListener(this);  12         button1.setTag(1);  13         button2.setOnClickListener(this);  14         button2.setTag(2);  15         button3.setOnClickListener(this);  16         button3.setTag(3);  17           18   19     }  20     public void onClick(View v){  21         int tag = (Integer) v.getTag();  22         switch(tag){  23         case 1:  24             Intent music = new Intent(Intent.ACTION_GET_CONTENT);  25             music.setType("audio/*");  26             startActivity(Intent.createChooser(music, "Select music"));  27             break;  28         case 2:  29             Intent dial = new Intent();  30             dial.setAction("android.intent.action.CALL");  31             dial.setData(Uri.parse("tel:13428720000"));  32             startActivity(dial);  33             break;  34         case 3:  35             Intent wallpaper = new Intent(Intent.ACTION_SET_WALLPAPER);  36             startActivity(Intent.createChooser(wallpaper, "Select Wallpaper"));  37             break;  38         default :  39             break;  40         }  41   42     }  43 }