Reputation: 1
When working with java in Android Studio, how do I get back from a fragment to a previous fragment?
This is the code I added to MainActivity.
**public void onBackPressed() {
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
for(Fragment fragment : fragmentList){
if(fragment instanceof onBackPressedListener){
((onBackPressedListener)fragment).onBackPressed();
return;
}
}
if(System.currentTimeMillis() - lastTimeBackPressed < 1500){
finish();
return;
}
lastTimeBackPressed = System.currentTimeMillis();
Toast.makeText(this,"Press the 'Back' button again to finish.",Toast.LENGTH_SHORT).show();
}**
And can the page that receives information from being entered in a different way than a fragment?
Is it possible to delete the fragment while storing the input information after it is input from the fragment? When I go back, the stack is still piled up, so I keep seeing the previously entered information.
Upvotes: 0
Views: 49
Reputation: 13458
For the fragment you add that allows the user to input information, make sure to call:
fragmentTransaction.addToBackStack(null);
during the fragment transaction where you add the fragment.
Then get rid of the onBackPressed
override, it's not necessary.
addToBackStack()
will enable automatic handling of the BACK button press, removing the fragment transaction.
Upvotes: 1