【发布时间】:2016-11-18 05:15:51
【问题描述】:
所以我有一个 xml,它由一个线性布局组成,其中包含一个 Button 和一个 TextView,如下所示:
<?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="100dp"
android:orientation="vertical">
<Button
android:id="@+id/btnCell"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:paddingLeft="40dp"
android:text="Button"
android:textColor="@color/blueText" />
<View
android:height="wrap_content"
android:width="wrap_content"
android:background="@drawable/Test"/>
</LinearLayout>
我想在不同的 xml 中的其他布局中使用相同的布局。我每次都需要同一个按钮,所以我通过将它包含在两个布局中来重用它(两个布局都在同一个 xml 中,但隐藏了一个):
第一个
<?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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image"
/>
<include layout="@layout/buttonLayout"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
第二个:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image"
/>
<include layout="@layout/buttonLayout"/>
<CheckBox
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
所以我在应用程序的开头显示第一个布局并隐藏第二个布局,当用户在界面内移动时,布局交换以便显示另一个布局并隐藏第一个布局。
问题是我在我的 java 活动类中声明了 Button,如下所示:
btnCell = (Button) thirdView.findViewById(R.id.btnCell);
btnCell.setOnClickListener(this);
并实现了监听器。
@Override
public void onClick(View v) {
if (v == btnCell) {
System.out.println("entered if");
}
System.out.println("entered function");
}
问题是,当我在显示第一个视图并隐藏第二个视图时单击按钮时,该按钮工作得很好,但是当我取消隐藏第二个布局时,隐藏第一个布局,然后继续单击按钮,即应该与第一个相同,但布局不同,没有任何反应。我搜索并发现,发生这种情况是因为由于视图层次结构,id 仅分配给第一个布局中显示的按钮,而不是第二个布局中的那个。如何让两个按钮对相同的操作做出反应,而不在每个布局中声明一个新按钮,而是重复使用它?
【问题讨论】:
标签: android android-layout android-studio layout