子片段触发父片段的onClick事件

4
我正在使用嵌套片段,并通过代码从一个片段传递到另一个片段。
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>

有人知道为什么会发生这种情况吗?

是的,这种情况也发生在我身上。唯一的解决方案是在事务期间删除父片段(您可以将其添加到返回堆栈中)。 - Hirak Chhatbar
1个回答

4

Reason: if you don't intercept/handle click in the child fragment - it will be passed to the parent fragment. Even if you handle clicks on some elements it doesn't change the whole situation.

Easiest solution: to avoid this behavior - declare most outer layout of your child fragment clickable like this:

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

You don't even have to implement onClickListener in this case


您可以处理特定元素上的点击事件。如果您点击这些元素,点击事件不会传递到父片段。但是,如果您在其他任何地方点击,它将会传递到父片段。因此,请尝试我的建议。如果不起作用,我会再考虑一下。 - sberezin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接