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

以编程方式为场景中的按钮设置onClickListeners

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

以编程方式为场景中的按钮设置onClickListeners

通常,对同一视图具有多个视图不是一个好主意

id
。这就是造成混乱的原因。

注意:以下是OP使用的适合其特定需求的解决方案:

一种简单的解决方案是使用

onClick
XML文件中的属性。您可以将相同的onClick方法分配给多个项目。像这样:

并在您的activity.java中添加以下内容:

public void buttonClicked(View v){    Log.d("TAG","Button clicked!!"    // do stuff here}

第二个选择

当您使用的设置一个按钮的侦听器

id
button_1
,不会同时设置
listener
两个按钮的监听器,而只会为第一个按钮设置监听器。如果要
listener
为两者都设置相同的值,则要做的就是将这些按钮分配不同
ids
,然后将它们分配相同
listener

这是您应该做的:

Listener myListener = new Listener(){.. blah blah....};((Button) findViewById(R.id.some_id)).setListerner(myListener);((Button) findViewById(R.id.some_other_id)).setListerner(myListener);

第三种选择

findViewById(R.id.id_of_layout1).findViewById(R.id.button_1)findViewById(R.id.id_of_layout2).findViewById(R.id.button_1)

在这种情况下,您需要向布局文件中添加一些ID,例如:layout_1.xml:

<RelativeLayout        android:id="+id/id_of_layout1"        android:layout_width="wrap_content"        android:layout_height="wrap_content">    <Button        android:id="@+id/button_1"        android:text="button2"        android:background="@android:color/black"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    </RelativeLayout>


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

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

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