In the XML file "display the onClick attribute of the specified button, so that when the button is clicked, the click() method in the corresponding Activity will be called by reflection"
<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" />
Here, when you finish typing android:, press Alt+/, there will be a prompt for the onClick attribute
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); } // Note that there is no @Override tag here 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; } } }
In this way, the click event of the button can be realized without declaring the button in the whole code.