I'm developing an app where I have a menu with Buttons, and in each Button the user go through Fragments. When I press the back Button of the phone (the first of three buttons of the device, the arrow) it goes to the previous Fragment, but I want to go back to the menuscreen.
How can I program that Button to open the menu activity?
Asked
Active
Viewed 44 times
0
Vadim Kotov
- 8,084
- 8
- 48
- 62
Mauro Stancato
- 537
- 1
- 9
- 19
-
Check I have updated my answer, hope it helps, consider accepting if it works for you, ask for clarification otherwise – Jasurbek Jul 10 '19 at 05:02
3 Answers
2
You may try overriding onBackPressed() and then routing all back presses to the menu activity:
@Override
public void onBackPressed() {
Intent goToMenuActivity = new Intent(getApplicationContext(), YourActivity.class);
startActivity(goToMenuActivity);
}
Tim Biegeleisen
- 502,043
- 27
- 286
- 360
1
When I press the back button of the phone (the first of three buttons of the device, the arrow) it goes to the previous fragment
That means you are using back-stack for your fragments.
First Solution
The simple solution is just removing (not using) back-stack
Second Solution
override OnBackStack then manipulate your activity
@Override
public void onBackPressed() {
finish();
startActivity(new Intent(this, MenuActivity.class));
}
Third solution
it requires more effort to implement but you may try. @MaximeJallu solution
1 - Create Interface
public interface IOnBackPressed {
/**
* If you return true the back press will not be taken into account, otherwise the activity will act naturally
* @return true if your processing has priority if not false
*/
boolean onBackPressed();
}
2 - Prepare your Activity
public class MyActivity extends Activity {
@Override public void onBackPressed() {
Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
if (!(fragment instanceof IOnBackPressed) || !((IOnBackPressed) fragment).onBackPressed()) {
super.onBackPressed();
}
} ...
}
Finally in your Fragment:
public class MyFragment extends Fragment implements IOnBackPressed{
@Override
public boolean onBackPressed() {
if (myCondition) {
//action not popBackStack
return true;
} else {
return false;
}
}
}
Jasurbek
- 2,946
- 3
- 20
- 37
0
There is two methods
link this 1
@override
public void onBackPressed(){
super.onBackPressed();
finish();
}
2
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
return false;
}
return super.onKeyDown(keyCode, event);
}
Chanaka Weerasinghe
- 5,404
- 2
- 26
- 39