I have Fragments (A, B, C) in Navigation Drawer Activity and subfragments (A2, A3, B2, B3) respectively to Fragments A and B. I need them to work like this: 1) A -> B -> C -> B. when I press the back button, then I need to return A. That is, Fragment A is the main 2) A-> A2-> A3 When I press the back button then I need to return A2, then A. I tried to use addToBackStack(), it helps on the second example, but not the first example. So,help me guys,thanks a lot))) (Sorry for my not understandable English)
Asked
Active
Viewed 311 times
0
-
you can check this [Link](https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press) – Jaydip Radadiya Jun 28 '18 at 05:35
-
Give the transaction a tag. And pop to tag exclusive. – EpicPandaForce Jun 28 '18 at 05:35
2 Answers
1
Step 1. Make One Interface Like this
public interface HostInterface {
void changeCurrentFragmentTo(int currentFragmentId, Bundle bundle);
}
implement it in your Main Activity.
Step 2. In your fragment
private HostInterface hostInterface;
@Override
public void onAttach(Context context) {
super.onAttach(context);
hostInterface = (HostInterface) context;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getView() != null) {
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
**hostInterface.changeCurrentFragmentTo(yorfragment,null);**
return true;
}
}
return false;
}
});
}
}
Step 3. Now you got call back in Activity
. Call New Fragment
as per your Requirement

VIISHRUT MAVANII
- 11,410
- 7
- 34
- 49
-
I must call the fragment with replace method or add?And I must add addToBackStack(null)? – Mukhit Jul 02 '18 at 05:21
-
Thank you, it helped me.I call interface in activity and wrote several "if" cases – Mukhit Jul 02 '18 at 05:48
-
0
You could use the FragmentManager you directly address the fragment you want to show or hide.
var newFragmentTag = typeof(NewFragment).Name;
var newFragment = FragmentManager.FindFragmentByTag(newFragmentTag);
if(newFragment != null)
{
FragmentManager.BeginTransaction().Hide(currentFragment).Show(newFragment).Commit();
}
else
{
// new Instance of newFragment and hide/show ...
}

Aiko West
- 791
- 1
- 10
- 30