gpt4 book ai didi

android - 子 fragment 触发父级的 onClick

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:59 24 4
gpt4 key购买 nike

我正在使用嵌套 fragment ,通过代码从一个 fragment 传递到另一个 fragment

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();
}
});

然而,有时我仍然可以从子 fragment 中点击父 fragment 的项目,即使它们是不可见的(被子 fragment 覆盖)。特别是,当 child 具有简单的 type 布局时会发生这种情况

<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>

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

最佳答案

原因:如果您不拦截/处理子 fragment 中的点击 - 它将传递给父 fragment 。即使您处理了对一些元素的点击,它也不会改变整个情况。

最简单的解决方案:要避免这种行为 - 声明您的 fragment 的最外层布局 可以像这样点击:

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

在这种情况下你甚至不必实现onClickListener

关于android - 子 fragment 触发父级的 onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com