【问题标题】:Back Stack count increasing when clicked on fragment in background在后台单击片段时返回堆栈计数增加
【发布时间】:2019-11-13 06:12:28
【问题描述】:

单击每个片段中的 textView 时,我正在添加下一个片段。

我的流程是 MainActivity => 片段 A => 片段 B => 片段 C => 片段 D

但是每次我在 Fragment D 中单击 textView 时,都会添加 Fragment D 并且返回堆栈计数会增加。 我在 Fragment D 中没有任何点击监听器。那么为什么会这样呢?

这是我的 MainActivity =>

    buttonAddFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AFragment fragment = new AFragment();
            addFragment(fragment, "MainActivity");
        }
    });


public void addFragment(Fragment fragment, String callingFrom) {
    Log.e("Call =>", callingFrom);
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.fragmentContainer, fragment, "demoFragment");
    fragmentTransaction.addToBackStack("tag");
    fragmentTransaction.commit();
}

片段 A =>

    mTextViewClick = view.findViewById(R.id.mTextViewClick);
    mTextViewClick.setText("A Fragment");
    mTextViewClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BFragment fragment=new BFragment();
            ((MainActivity)getActivity()).addFragment(fragment,"Fragment A");
        }
    });

所有片段的代码都与片段 A 相同

【问题讨论】:

标签: android android-fragments fragment-backstack


【解决方案1】:

这里发生的事情实际上是点击片段 C,因为没有在片段 D 的视图上声明触摸消费者,并且由于您使用的是 FragmentTransaction.add() 函数,因此之前的片段视图不会被破坏或被新片段替换。

因此,要解决此问题,您只需将这些属性添加到片段 D 的根视图:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    android:focusable="true"
    android:clickable="true"
    android:focusableInTouchMode="true">
    ....
</RelativeLayout>

或者确保您已经使用FragmentTransaction.replace() 方法替换了之前的片段视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多