I want to completely it goes to the home of the phone when i back, but onBackPressed() is not working.
My Page is a fragment btw.
Use getActivity().onBackPressed(); in your fragment it will execute onBackPressed() of your parent activity
to be more accurate
Activity activity = getActivity();
if (activity != null) {
activity.onBackPressed();}
edit: use requireActivity() for avoiding nullpointer
requireActivity().onBackPressed();
onBackPressed callback is handled by your parent activity. So you can override callback on parent activity
XyzActivity.java:
#Override
public void onBackPressed() {
handleBackPress();
}
public void handleBackPress() {
Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.fragmentFrameLayout);
if (visibleFragment == null) {
return;
}else if (visibleFragment instanceof PreviewFragment) {
CommonFunctions.showDialogActionable(this, "Confirm", "Are you sure you want to exit?",
"Yes", (dialogInterface, i) -> {
finish();
}, "No", null, "", null, true);
return;
}else
finish();
super.onBackPressed();
}
Related
I have taken one activity and with activity I have attached navigation drawer and the home fragment. In that navigation drawer there is a option of "Contact Us". When user click on that option a fragment gets open. But I am not able to maintain the stack of that. means when I am on contact us fragment then using navigation drawer again click on contact us it overlaps previous one. I have to press back button 2 times to go on home fragment. Please Help me how to maintain back stack for this. Here is my code..
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.rate:
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(myAppLinkToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Unable to find source market app!", Toast.LENGTH_SHORT).show();
}
break;
case R.id.contact_us:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container_dashboard, ContactUsFragment.newInstance());
transaction.addToBackStack(null);
transaction.commit();
mDrawerLayout.closeDrawer(GravityCompat.START);
break;
}
return false;
}
});
After this code I use this to maintain back stack:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
}
else new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Dashboard.super.onBackPressed();
}
})
.setNegativeButton("No", null)
.show();
}
But the issue is It's show exit dialogue on contact us fragment when ever I press back button. But I want firstly I reach to home fragment and after that If I press back button then it show exit dialogue.
I solved this by adding this in the onCreate method.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0){
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
menuToggle.setDrawerIndicatorEnabled(true);
// your dialog
}else{
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
menuToggle.setDrawerIndicatorEnabled(false);
// remove to your previous fragment
}
}
});
For so far. I have created a simple quiz application on Android Studio. Everything works fine, including when I go from the FirstActivity.java to the Next Activity, which is named SecondActivity.java, and close the first activity with finish(),when the button is pressed, as shown in the following code:
public void onClick () {
button_next = (Button)findViewById(R.id.nextbtn);
button_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
finish();
}
});
The code works great But when I try to go from the Second Activity to the First Activity (Closing the Second Activity and going back to the first Activity), neither finish() nor onBackPressed() is working, it just closes the application completely, what code do I need to as soon as I press the button, close the SecondActivity.class and go to the FirstActivity.class?
If you want to go back to previous activity, dont put finish after you change your activity.
public void onClick() {
button_next = (Button) findViewById(R.id.nextbtn);
button_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
}
});
}
If you have so many activities ,there is another way handle activity life cycle:
public class MyActivityManager {
private static MyActivityManager instance;
private Stack<Activity> activityStack;//activity's stack
private MyActivityManager() {
}
//singleton
public static MyActivityManager getInstance() {
if (instance == null) {
instance = new MyActivityManager();
}
return instance;
}
//push an activity to stack
public void pushOneActivity(Activity actvity) {
if (activityStack == null) {
activityStack = new Stack<Activity>();
}
activityStack.add(actvity);
}
//get last activity,fifo
public Activity getLastActivity() {
return activityStack.lastElement();
}
//remove an activity
public void popOneActivity(Activity activity) {
if (activityStack != null && activityStack.size() > 0) {
if (activity != null) {
activity.finish();
activityStack.remove(activity);
activity = null;
}
}
}
//finish all activity
public void finishAllActivity() {
if (activityStack != null) {
while (activityStack.size() > 0) {
Activity activity = getLastActivity();
if (activity == null) break;
popOneActivity(activity);
}
}
}
}
at the FirstActivity,you shall add
MyActivityManager.getInstance().pushOneActivity(FirstActivity.this);
at the SecondActivity, you want to go FirstActivity or other activity:
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
MyActivityManager.getInstance().finishAllActivity();
finish();
I have two layouts, A and B. The app launches the A_layout, and through a button you can go to the B_layout. On default when you press the back button the app closes, doesnt matter if the app is on the A or B layout. When I override the back button to set the content view always on the layout A whenever the back button is pressed, then I cant open the B activity anymore through the button. How do I need to override the method correctly? :)
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
setContentView(R.layout.activity_main);
return true;
}
return super.onKeyDown(keyCode, event);
}
activity_main = A layout
Do I need to make Intents there?
You can override the onBackPressed function:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), ActivityA.class);
startActivity(intent);
finish();
}
When finsihing the activity is destroyed
I am trying to implement onBackPressed on an activity with 3 Fragments. My issue is I implemented a "press again to exit" after some time method however when back button is clicked twice it returns to the previous fragment, not quitting. This happens when that fragment is called (i.e if I open the game and exit straight away it works like a charm). My onBackPressed method on MainActivity looks like this;
#Override
public void onBackPressed() {
if(getSupportFragmentManager().getBackStackEntryCount()!=0) {
getSupportFragmentManager().popBackStack();
}
this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
if(mBackPressed + TIME_INTERVAL > System.currentTimeMillis() && getSupportFragmentManager().getBackStackEntryCount()==0){
super.onBackPressed();
System.exit(0);
this.finish();
}
else { Toast.makeText(getBaseContext(), "Press back once more to exit", Toast.LENGTH_SHORT).show(); }
mBackPressed = System.currentTimeMillis();
}
I basically want to check if the user is in the mainActivity layout so I could evade using popBackStack. Any solution would be appreciated, I could provide more information if this is not enough.
Thanks,
Bektaş
If you really want to quit, ignore the back stack altogether. Use this code.
#Override
public void onBackPressed() {
this.findViewById(R.id.linearLayout1).setVisibility(View.VISIBLE);
if(mBackPressed + TIME_INTERVAL > System.currentTimeMillis()){
this.finish();
return;
}
else {
Toast.makeText(getBaseContext(), "Press back once more to exit", Toast.LENGTH_SHORT).show();
}
mBackPressed = System.currentTimeMillis();
}
I think you might find this link useful
http://developer.android.com/training/implementing-navigation/temporal.html
it says that you can add the reference to the stack using this paturn
// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
getSupportFragmentManager().popBackStack(getSupportFragmentManager().getBackStackEntryCount(), getSupportFragmentManager().POP_BACK_STACK_INCLUSIVE);
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(context);
builder.setCancelable(false);
builder.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
(Main Activity Name).super.onBackPressed();
}
}).create().show();
} else {
super.onBackPressed();
}
}
I have a MainActivity and I am posting partial code here:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_quit:
moveTaskToBack(true);
return true;
case R.id.action_help:
//display the help activity
Intent myIntent = new Intent( this, ShowHelp.class);
startActivityForResult(myIntent, 0);
return true;
case R.id.action_about:
//display the about window
//aboutApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void aboutApp() {
// custom dialog
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.about);
dialog.setTitle("About TollCulator");
TextView textViewAbout = (TextView) dialog.findViewById(R.id.tvContents);
textViewAbout.setText("About: ");
textViewAbout.append("\n\tTollCulator - Toll Calculator");
textViewAbout.setMovementMethod(new ScrollingMovementMethod());
Button btnCloseIt = (Button) dialog.findViewById(R.id.btnOk);
// if button is clicked, close the custom dialog
btnCloseIt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ImageView iv1 = (ImageView) dialog.findViewById(R.id.imgFB);
iv1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("https://www.facebook.com/PagesByZ"););
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
dialog.cancel();
startActivity(intent);
}
});
dialog.show();
}
ShowHelp.class partial code here which is an Activity on it's own:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 16908332:
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
//finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// do something on back.
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
//finish();
return;
}
Now when i choose action_help from the menu it opens the ShowClass Activity and I can press the back button and it brings me back to MainActivity without any problem.
Now If I choose action_about the About Dialog pops up and If I click on the icon within the Dialog the following pops up:
At this time If I decide to press BACK, instead of closing the pop and displaying my About Dialog, I am just taken to the Homescreen.
Commenting the finish(); method in ShowClass allows me to click the BACK button from the "Complete action using" But instead of taking me to the MainActivity, it takes me to ShowClass from there I can press the Back button again to come back to MainActivity. So as long as I choose action_help first, pressing back brings me back to the ShowHelp.
When the Complete action using pops up from the About Dialog, I set up a Log, and it's on the onPause() state and if I did not run ShowHelp in the beginning, my App goes directly to onStop() and onDestroy().
Please help me fix the issue.
To test it, I created a demo without the ShowHelp class with just the dialog and By pressing back button, the Complete actiong using dialog closes and then pressing back again closes the About Dialog. So I am not sure what is going on.
Declare a global boolean variable chooserIsShowing:
boolean chooserIsShowing;
Set it to true here:
ImageView iv1 = (ImageView) dialog.findViewById(R.id.imgFB);
iv1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// set the flag
chooserIsShowing = true;
Uri uri = Uri.parse("https://www.facebook.com/PagesByZ"););
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
dialog.cancel();
startActivity(intent);
}
});
Change the overriden onBackPressed() method:
#Override
public void onBackPressed() {
if (!chooserIsShowing) {
// do something on back.
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
finish();
}
// remove the flag
chooserIsShowing = false;
return;
}
Edit 1:
Declare dialog as a global variable:
Dialog dialog;
Change aboutApp():
public void aboutApp() {
dialog = new Dialog(this);
....
}
Override onKeyDown(int, KeyEvent) method in MainActivity:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
You can remove chooserIsShowing as its not required.
Final Solution:
A noHistory flag was defined for this activity in the manifest. Removing that and fixing onBackPressed() method of ShowHelp resolved the issue.