1

I am adding the next fragment when clicked on textView in each fragment.

My Flow is MainActivity => Fragment A => Fragment B => Fragment C => Fragment D

But every time I click on textView in Fragment D, Fragment D gets added and back stack count increases. I don't have any click listener in Fragment D. So why this is happing?

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

Fragment 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");
        }
    });

All fragments have the same code as Fragment A

1 Answers1

2

What's happening here is actually clicking on fragment C cause there is no touch consumer declared on the view of fragment D and since you are using FragmentTransaction.add() function the previous fragment view does not get destroyed or replaced with the new fragment.

So to fix this you can simply add these attributes to the root view of fragment D:

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

Or make sure you have replaced the previous fragment view using FragmentTransaction.replace() method.

Sdghasemi
  • 5,370
  • 1
  • 34
  • 42