栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Android的一个OnClick方法有多个按钮?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android的一个OnClick方法有多个按钮?

如果要减少编码行,请使用

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/508369.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号