子片段触发onClick的父级

时间:2014-11-15 16:35:59

标签: android android-fragments

我正在使用嵌套片段,使用代码

从一个片段传递到另一个片段
ImageView search = (ImageView) root.findViewById(R.id.search);
    search.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
            FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
            transaction.addToBackStack(null);
            transaction.replace(R.id.parent, ChildFragment.newInstance());
            transaction.commit();               
        }           
    });

然而,有时会发生从子片段中我仍然可以单击父片段的项目,即使它们是不可见的(由子片段覆盖)。特别是,当孩子具有类型

的简单布局时,会发生这种情况
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"  
    android:background="#FFF0D1"
    android:id="@+id/child">

...some stuff...    

</RelativeLayout>

但是当我使用嵌套布局时不会发生这种情况

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"  
    android:background="#FFF0D1"
    android:id="@+id/child">

<ScrollView
    android:id="@+id/scr"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:padding="10dp">

<RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

...same stuff...

</RelativeLayout>

</ScrollView>

</RelativeLayout>

有人知道为什么会这样吗?

1 个答案:

答案 0 :(得分:4)

原因:如果您没有拦截/处理子片段中的点击 - 它将被传递给父片段。即使您处理某些元素的点击,也不会改变整个情况。

最简单的解决方案:避免此行为 - 声明< 片段的强>最外层布局可点击,如下所示:

    <RelativeLayout
    ...
    android:clickable="true"
    ...>    
    ...

在这种情况下,您甚至不必实施onClickListener

相关问题