[英]Android: Add view into another while having a click listener on the parent
我正在尝试实现以下层次结构:GridView->每个项目都是一个包含背景,ImageView和CheckBox的视图(我们称之为“容器”)。
如果用户单击容器,则无论是在复选框,图像还是背景上,复选框都应在何处更改其选中状态。
现在,我有以下布局:
<!-- main layout -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:id="@+id/selectBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Select" android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:minWidth="200dp" />
<GridView android:id="@+id/imageGridView"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center"
android:layout_above="@id/selectBtn" />
</RelativeLayout>
<!-- gallery item layout - every grid item is inflated from this -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView
android:id="@+id/thumbImage"
android:layout_width="110dp"
android:layout_height="110dp"
android:background="#999999"
android:layout_centerInParent="true"
android:contentDescription="image thumb"/>
<CheckBox
android:id="@+id/itemCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
之后,我希望能够检索已检查的容器。
我真的不知道如何创建这种布局。 即使我的布局现在看起来不错,也没有“容器”会对点击侦听器做出反应。 我只能使复选框对单击做出反应,这当然不是很友好。 那么如何在这些视图周围添加一个包装容器以供单击呢? 非常感谢!
啊,没关系...随着RelativeLayout扩展View和ViewGroup,我可以使用类似以下内容的方法:
RelativeLayout container = (RelativeLayout) holder.imageview.getParent();
container.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("test", "clicked");
RelativeLayout cont = (RelativeLayout) v;
CheckBox cb = (CheckBox) cont.getChildAt(1);
if(cb.isChecked()) cb.setChecked(false);
else cb.setChecked(true);
}
});
您还可以使用GridView的setOnItemClickListener()方法来设置项目的点击侦听器(图像+复选框)。 在侦听器内部,您可以更改复选框的选中状态。 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.