2
I have a main activity in which are called some Fragments:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listas);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentUm fragment_um = new FragmentUm();
ft.add(R.id.fragment, fragment_um).commit();
}
When loading fragment_um in this Activity I have a Recyclerview where I click on an item that can direct me to activity_details or call fragment_two:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentDois fragment_dois = new FragmentDois();
ft.addToBackStack(null);
ft.replace(R.id.fragment, fragment_dois).commit();
By loading fragment_two I have a Recyclerview that by clicking on an item in the list can direct me to fragment_tres or to activity_details. Fragment_tres I have the same situation.
In the manifest the main Activity is configured to show the home button on Toolbar:
android:parentActivityName=".MainActivity"
However, if you have fragment_two clicked on Activity and click the home button, I cannot go back to fragment_one. The same thing happens if you are in fragment_tres and click on the home button, I cannot go back to fragment_dois.
I tried to use getFragmentManager().popBackStack()
or getFragmentManager().popBackStackImmediate()
within the onOptionsItemSelected(MenuItem item)
but it didn’t work out.
My question is, what do I have to do to get back to the previous Fragment from any of them?
I made some changes to the code:
In the main Activity I use the onBackPressed() class for when clicking on the home icon, through onOptionsItemSelected(Menuitem item), to go back to the previous Fragment:
@Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
}
I have removed from the manifest the configuration I mentioned earlier. In onViewCreated from Fragments I implemented this code to programmatically display the home icon in Actionbar. In Fragment 1 it is false and in the other true:
ActionBar actionbar=((AppCompatActivity)getActivity()).getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
It is working, however it is showing an alert that getSupportActionBar and setDisplayHomeAsUpEnabled can generate a Nullpointerexception. You can fix it?
I tried to use the example you indicated but in my case it didn’t work. With this example, when clicking the home button nothing happens.
– Henqsan