I have a main activity in which some fragments are called:
@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 I load the fragment_um in this Activity I have a RecyclerView where I click on an item that can direct me to the activity_detalhes or call the fragment_dois:
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FragmentDois fragment_dois = new FragmentDois();
ft.addToBackStack(null);
ft.replace(R.id.fragment, fragment_dois).commit();
When loading the fragment_dois I have a RecyclerView which when clicking on an item in the list can direct me to the fragment_tres or to the activity_detalhes. The fragment_tres I have the same situation.
No manifest the main activity is configured to show the home button in the toolbar:
android:parentActivityName=".MainActivity"
However, if you have fragment_load loaded in activity and click the home button, I can not get back to fragment_um. The same thing happens if you are in fragment_tres and click the home button, I can not get back to the fragment_dois.
I tried to use getFragmentManager().popBackStack()
or getFragmentManager().popBackStackImmediate()
within onOptionsItemSelected(MenuItem item)
but it did not work.
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 when I click the home icon, through the onOptionsItemSelected (MenuItem item), go back to the previous fragment:
@Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
}
I removed the manifest I mentioned earlier from the manifest. In the fragmented onViewCreated I implemented this code to programmatically show the home icon in ActionBar. In fragment 1 it becomes false and in the others 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. Can you solve this?