android - 是否可以在一个布局中制作两个具有相同 ID 的按钮?

标签 android android-layout android-button

是否可以在一个布局中制作两个具有相同 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/

相关文章:

带有图标的 Android 圆形按钮

android - 如何在移动网络应用程序上使用 mailto

安卓与linux的关系

android - WebView 未加载网页

java - 为什么在 android 中将 Width 和 Height 设置为 wrap_content 后,我​​的 EditText 会水平或垂直扩展?

Android点击时更改背景颜色

android - 如何删除 Material 设计按钮中的额外填充或边距?

android - div 高度标签中的设计问题?

java - 如何处理具有由嵌套布局组成的组 View 的 ExpandableListView 的触摸

java - Android EditText - 使用按钮删除最后一个字母