user370305..
24
如果你想减少编码行然后使用View's OnClick() with switch statement,如果你想单独处理所有点击(为了便于理解和维护代码),然后使用单独的所有button's onClick().
更新:
如果已在Activity布局xml文件中声明了Buttons,android:onClick=""则为所有按钮的write属性设置相同的方法名称,并在活动中实现该方法.现在,您有一个所有按钮的方法,并在该方法中区分具有id的按钮.
例:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 1" />
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 2" />
android:layout_width="wrap_content"
android:onClick="buttonOnClick"
android:layout_height="wrap_content"
android:text="Hello, I am a Button 3" />
现在在你的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.