是否可以在一个布局中制作两个具有相同 id 的按钮?
我试图通过标签 <include>
来做, 但不适用于听众之一的按钮
最佳答案
编辑 2016 年:
这不再可能了,android lint 检查会阻止您在同一个 xml 文件中添加相同的 id。
解决方法是使用 include
标记来包含其他具有重复 ID 的 xml。
然而,这是一种应该避免的方法。
旧答案
长话短说:博士; View Container中只能有distince ids,如果你再创建一个container,你可以使用parent.findViewById(R.id.child_id)
;
虽然您的用例在设计层面上似乎存在缺陷,但这是可能的
<LinearLayout
android:id="@+id/parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="30dp">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<RelativeLayout
android:id="@+id/button_2"
android: layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/second_buttonLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="@layout/title_bar" />
</RelativeLayout>
</LinearLayout>
为了给两个按钮设置监听器,
findViewById(R.id.button1); //referring to first button
((RelativeLayout)findViewById(R.id.button_2)).findViewById(R.id.button_of_include) //referring to second button
EDIT 基于 OP's answer , 关键点 是为包含 include 的父布局提供一个 id。这将允许您引用该布局及其子布局。即:
<RelativeLayout
android:id="@+id/button_2"
android: layout_width="80dp"
android:layout_height="80dp">
<include
android:layout_width="80dp"
android:layout_height="80dp"
layout="@layout/include_layout" />
</RelativeLayout>
关于android - 是否可以在一个布局中制作两个具有相同 ID 的按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621012/