如果要减少编码行,请使用
View's onClick() with switchstatement;如果要单独处理所有单击(为便于理解和维护代码),请分别使用所有
button's onClick().
更新:
如果在“活动”布局xml文件中声明了Buttons,则应
android:onClick=""为所有按钮编写具有相同方法名称的属性,并在Activity中实现该方法。现在,您为所有按钮提供了一种方法,在该方法中,可以区分带有id的按钮。
例:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:onClick="buttonOnClick" android:layout_height="wrap_content" android:text="Hello, I am a Button 1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:onClick="buttonOnClick" android:layout_height="wrap_content" android:text="Hello, I am a Button 2" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:onClick="buttonOnClick" android:layout_height="wrap_content" android:text="Hello, I am a Button 3" /></LinearLayout>
现在在您的Activity实施中
buttonOnClick,
public void buttonOnClick(View view){ switch(view.getId()) { case R.id.button1: // Code for button 1 click break; case R.id.button2: // Code for button 2 click break; case R.id.button3: // Code for button 3 click break; }}或者,您可以对活动中动态添加的按钮应用相同的开关盒,例如,而不是
buttonOnClick必须使用
实现的View的OnClickListerner
onClick。



