I'm adding a fragment to an activity instead of replacing the current fragment (because this corresponds to the type of behavior I want to have).
My problem is that clicking in a spot on the top fragment (the one that's currently visible), where a view in the non-visible fragment is located, causes an onClick event on the view in the second, non-visible fragment, to fire. Why is this happening and how can I prevent this?
This is the code I use to first add the ListView fragment to the activity:
@Override protected void onCreate(Bundle savedInstanceState) { ... if (savedInstanceState == null) { listFragment = new ListFragment (); getSupportFragmentManager().beginTransaction() .add(R.id.frame_container, listFragment) .addToBackStack(listFragment .TAG) .commit(); } ... }
In this same activity I'm adding the second fragment, on top of the list fragment:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... createItemFragment = new CreateItemFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.frame_container, createItemFragment) .addToBackStack(createItemFragment.TAG) .commit(); ... }
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.
You can just add the following attribute to the XML root layout of the fragment that agoes on top-
android:clickable="true"
This will ensure that touch events will not propagate further than the top layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With