android -> 简洁的办法 给 XML 中的 所有 Button 绑定 点击 事件

在XML文件中“显示指定按钮的onClick属性,这样点击按钮时会利用反射的方式调用对应Activity中的click()方法”

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="Button1" />
 
  <Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:text="Button2" />

 

这里在输完android:的时候按下 Alt+/ 会有 onClick 属性的提示

public class TestButtonActivity extends Activity {
 
  Button btn1, btn2;
  Toast tst;
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test_button);
  }
 
  // 注意 这里没有 @Override 标签
  public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.button1:
      tst = Toast.makeText(this, "111111111", Toast.LENGTH_SHORT);
      tst.show();
      break;
    case R.id.button2:
      tst = Toast.makeText(this, "222222222", Toast.LENGTH_SHORT);
      tst.show();
      break;
    default:
      break;
    }
  }
}

 

这种写法整个代码中都不用声明button就可以实现button的单击事件

猜你喜欢

转载自mft.iteye.com/blog/2337830