android的多个按钮实现方法,Android一个用于多个按钮的OnClick方法?

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.

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值