Create custom BackKey to navigate through framents - android

I got the next FragmentActivity. This FragmentActivity inflates a layout with a LinearLayout(a menu where some buttons are defined to call other fragments) and a FrameLayout (a black space where the other fragments are loaded depending the button I select).
public class MenuViewActivity extends FragmentActivity {
....
I load the selected Fragment using onClickListener:
protected void onCreate(Bundle savedInstanceState) {
....
final OnClickListener fragment_1 = new OnClickListener() {
#Override
public void onClick(View v) {
fragment_1 Fragment = new fragment_1();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, Fragment);
transaction.addToBackStack(null);
transaction.commit();
}
};
I do this for about 5 buttons. This menu also contains a custom back key. The functionality of this back button should be like:
[fragment_1][fragmen_2][fragment_3][fragment_4][fragment_5]
The app starts always showing fragment_1. I con go from fragment_1 to any of the other fragments. So I could go for example from [fragment_1] to [fragment_4]. When pressing the back key I should go back to [fragment_1].
To detail a little bit more the functionality, I could do: [fragment_1]->[fragment_2]->[fragment_3] and when pressing back, should go back to [fragment_1].
I've got a onClickListener for the back key, but I don't know how to implement this functionality.

you're looking for this
getSupportFragmentManager().popBackStack();
also if you're unaware that's the default functionality for the actual android back button, so unless you've overrode it that will do the same thing.

You just need to pop all fragments from your backstack, unless you reach the one you want. It is probably simplest to use FragmentManager's popBackStack():
public abstract void popBackStack (int id, int flags)
Pop all back stack states up to the one with the given identifier

Related

Fragments stacking on each other

I have a problem with fragments. In my xml file I have a fragment already set there, I want with the click of a button replace it with another fragment. So with my code I can replace the fragment with the one that I want on the click of the button, but the first fragment wont disappear, so I can still see it under my second fragment, the code it's this:
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment,new BlankFragment2());
fragmentTransaction.addToBackStack(null).commit();
}
});
}
}
Set a background color of the root layout of the second fragment and put clickable and focusable true in xml file. It will make disappear of the first fragment and also disable the clicks of first fragment when showing another fragment.
Remove addToBackStack(null).
That stores the Fragment and keeps it attached so that calling popBackStack() will remove the top Fragment and replace it with the previous.
correctly implementing addToBackStack will help in this case and many other
addToBackStack takes an argument which is called task record TAG , To perform a transaction later on , you can use this tag to remove back stack up to a point
For more understanding read
https://medium.com/#bherbst/managing-the-fragment-back-stack-373e87e4ff62

Replace multiple fragments at the same time

I have an Activity with a navigation drawer. I have used fragments for this and when I'm moving to different menus in the drawer I add them to the backstack with addToBackStack() method. Basically, Activity starts with Fragment A then if I go to Fragment B or Fragment C I can press back and go back to Fragment A.
But now I have a notification which should open the Activity with Fragment B open and when I press back it should take me back to Fragment A. Is there a way to handle this like in startActivities.
Here is the code for the Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, new FragmentA()).commit();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
break;
case R.id.buttonB:
transactFragment(new FragmentB());
break;
...
}
}
private void transactFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.layoutContent, fragment).addToBackStack(fragment.getClass().getName()).commit();
}
Why not just define the fragments with tags and call them as you need to?
Here's a sample of how I work with my fragments:
Start your fragments in the Activity's onCreate() method, like so:
/** Load screen1 */
Instructions screen1 = new Instructions();
screen1.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().
add(com.example.tool.R.id.
instructions_container, screen1, "screen1").
addToBackStack(null).
commit();
Then you can grab them and show/hide them as much as you like:
/** screen 1 */
public void showInstructions()
{
// show screen 1
getFragmentManager().findFragmentByTag("screen1").
getView().setVisibility(View.VISIBLE);
}
In my project, we use a global enum to check which fragment is currently up, so we don't have to rely on the stack, which has more than once proven itself to be unreliable.
onBack calls a switch, which checks this enum and acts accordingly. For your use-case, you can just track when this notification has been called, so it will go from Fragment B, to Fragment A.

How to avoid Fragment going back to previous Fragment on pressing device back button?

I am developing an android in which when I pressed device back button I go to previous fragment. What I want to achieve is that when I pressed device back button I don't want to go to previous fragment. How can I achieve that?.
You must be doing calling addtobackstack("name") while adding or replacing the fragment.Remove this function before calling next fragment you wont go back to previous fragment for further desc
Do not add that fragment to backstack of the new fragment you're calling. Look at the below example I've used to explain you how this works.
To make that fragment come again, just add that fragment to backstack which you want to come on back pressed,
Eg:
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment = new LoginFragment();
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack("SignupFragment");
ft.commit();
}
}
});
In the above case, I m opening a LoginFragment when signIn button is pressed, right now am in SignupFragment. So if I call addToBackStack(TAG), TAG = "SignupFragment", then when back button is pressed in LoginFragment, we come to SignUpFragment.
Happy Coding!

Add fragment into backstack behind the topmost/showing fragment

I wonder if there's a way to add a fragment into the backstack just behind the showing fragment. So that when a user press "back button" the added fragment would show up to the user.
As per my knowledge I am not sure the Fragment Manager can do such things !
Step-1: Why don't you add the fragment tobackStack` when mounting the fragment to the container
Step-2: Next onBackpressedor click of any view just pop the fragment from the container
Here is a sample from another Stackoverflow answer
fragmentTransaction.addToBackStack("fragB");
fragmentTransaction.addToBackStack("fragC");
Then in Fragment_C, pop the back stack using the name ie.. fragB and include POP_BACK_STACK_INCLUSIVE
someButtonInC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack ("fragB", FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});

Show/Hide two fragments in a single Layout [Both fragments have a Google map each]

I have an activity with a relative layout; And have two different fragments. I show one fragment and switch to the next fragment on a button click vice verse.
// When button menu is clicked
OnClickListener btnClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentType==0){
InitThisFragment(1);
}else{
InitThisFragment(0);
}
}
};
public void InitThisFragment(int type){
Fragment newFragment;
if(type==0){
newFragment=new MainFragment();
}else{
newFragment=new JourneyFragment();
}
currentType=type;
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
R.id.abs_fragment_container is a Relative Layout
BOTH THE FRAGMENT CONTAIN GOOGLE MAPS INSIDE THEM;
But it is not working as expected.
By default i add the first fragment [which works fine].
Then after an onClick event the 2nd fragment comes[which also works
fine]
But on my next click the app crashes;
Please help I am new to Google Maps and Fragments;
yeah of course your app crashes because the fragment with the map already exists look at this thread it helped me a lot: Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment
Especially the second answer with 41 ups is easy to understand
And yes I would have posted this one in a comment if I would have enough reputation for it!

Categories

Resources