I'm using this template https://github.com/kanytu/android-material-drawer-template just to try out material design so I've implemented a few fragments some have webviews some have not.
My problem is when switching between the fragments I can see them being successfully added to the backstack
getFragmentManager().beginTransaction().replace(R.id.container, new FAQ()).addToBackStack("FAQ").commit();
But when I press the back button it just closes the app.
When I change it to use Activity instead of ActionBarActivity the navigation works fine but I lose some other functionality.
There is an override on the back button
#Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
but even if that's removed it still happens. I think the problem lies somewhere in the super.onBackPressed
Is there any reason ActionBarActivity would break the back button?
I recently read a post about this, sorry I can't find it anymore... But basically, it explained that the primary function of the back button is to finish the current Activity.
In fact, according to the onBackPressed() official documentation:
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
And it would appear that even though the back button used to pop the backstack before 5.0, Google would have changed this behaviour with the new ActionBarActivity.
For my part, I used some workarround that works for me but that might not work for everybody, depending on your navigation implementation.
But in case it could be helpful to somebody, here it is :
#Override
public void onBackPressed()
{
if (mDrawerLayout.isDrawerOpen()) {
mDrawerLayout.closeDrawer();
} else if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
This way, ActionBarActivity.onBackPressed() is only called when the backstack is empty, in which case it destroys the ActionBarActivity.
You should check "getFragmentManager" & "getSupportFragmentManager" is matched your activity & actionbaractivity or not.
Because, in Activity:
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
in FragmentActivity:
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
We can see the same code which already handled pop fragments backstatck.
In my situation, I used actionbaractivity(extends FragmentAcvitiy), but I also used "getFragmentManager" , so I got the same error as you. After I have replaced "getFragmentManager" to "getSupportFragmentManager", that's ok! You also can replace "actionbaractiviy" to "Activity" to fix this problem.
Must ensure "getFragmentManager" match "Activity", "getSupportFragmentManager" match "FragmentActivity(ActionbarActivity)".
If you want add actionbar On API level 11 or higher, You can see below:
https://developer.android.com/guide/topics/ui/actionbar.html#Adding
On API level 11 or higher
The action bar is included in all activities that use the Theme.Holo theme (or one of its descendants), which is the default theme when either the targetSdkVersion or minSdkVersion attribute is set to "11" or higher. If you don't want the action bar for an activity, set the activity theme to Theme.Holo.NoActionBar.
Related
Hello I am using this AppCompatDelegate to change between day/night themes
I have 2 activities A& B
this code called from activity B
it should recreating activity B & A with the chosen style
here is my code
applyNight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isNight) {
SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), true);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
SharedPrefrencesMethods.savePreferences(this, getString(R.string.night_key), false);
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
});
I tested it on android 7 & 6 it's working fine i.e when changing mode in activity B and press back activity A recreating with the new theme.
When trying it on android 9 it's changing the activity B only and not affecting it's parent activity A.
I was having that problem too, and then took the advice of Chris Banes in Google's official Android Developers blog https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94 to set setDefaultNightMode in the app's application class in the first place, so I created a class EcwgApplication extending Application as he shows, and added android:name=".EcwgApplication" in the application section of the manifest. I also put my method for switching themes in the application class as well, that my settings activity can call when the user changes the theme setting (in addition to updating SharedPreferences with the change before calling it), so it looks like this:
public class EcwgApplication extends Application {
public void onCreate() {
super.onCreate();
int selectedDarkLightTheme = PreferenceManager.getDefaultSharedPreferences(this).getInt(getString(R.string.preferences_dark_light_mode_selected_key), AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
}
public static void setDarkLightTheme(int selectedDarkLightTheme) {
AppCompatDelegate.setDefaultNightMode(selectedDarkLightTheme);
}
}
This worked fine with Android OS versions 24 through 29, but with 21 (the lowest version this app is supporting) through 23 I would get a black screen on returning to the first activity, and while rotating the screen would fix that, it also made clear that UI state was not being saved. So I changed the StartActivity for the Settings screen to StartActivityForResult, and in onActivityResult, check if the version number <= 23, and if so, do this.recreate().
I need to keep doing more testing, but at least so far everything seems to be working great.
I have a global navigation bar currently and it works beautifully unless the user hits the back button. I have overridden the back button like so
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
navBar.curr_position = navBar.position.pop();
Log.d("Backing To pos", Integer.toString(navBar.curr_position));
mDrawerList.setItemChecked(navBar.curr_position, true);
super.onBackPressed();
}
}
Where navBar.curr_position is the protected static int containing current position of the activity, and navBar.position is a protected static ArrayDeque (or stack) from my understanding.
All activities extend my base navBar class.
Now what I want the app to do, is when back is called to change the navBar's selection to whatever it was before. However it seems that with Android, when back is called it does not rerun any of the activity or base code so it simply never changes the selection.
Is there a function somewhere that can check to see if the program was just returned to from back and then change the navbar?
Thanks!
It turns out that I can put the setItemChecked code in onStart();
I am using navigation drawer in my MainActivity.java to switch fragments and I am also extending my MainActivity to the other activities in my app. Now the problem is that, when I press back button during I am on fragment, the app suddenly exits without any notification. And if I use OnBackPressed in my MainActivity it is bydefault implemented to the other activities extending main activity too and when I press back button to any of that acivity it asks me first for confirmation and then comes back to previous activity or frag. Need a solution to avoid this. I want to set onbackpessed or anything that shows dialogue or asks for confirmation to exit app on fragments only but dont know howto do.
Or any help regarding fragment back stacking to open a fixed fragment on back button pressed is welcomed if it tells how to change the title of hence opened fragment too.
call onBackPressed() in that activity in which you have put all fragment or main activity
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
//Display your dialog here
} else {
getFragmentManager().popBackStack();
}
}
Other solution
#Override
public void onBackPressed() {
if (slidingMenu.isMenuShowing()) {
slidingMenu.toggle(true);
} else {
super.onBackPressed();
//Display your dialog
}
}
This is works for me.
i know that may duplicate some threads but i can#t figure out what i wrong. I have slider dreawer where are fragments and in fragments there are webview. Everything is working fine at least one thing, namely when i press back button it closes the app. I have tried some other possible solutions but anything is not working. I even don't get any errors. I even tried this easy solution but without any progress
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
My Main activity:
And this is one of my fragments:
By default back button shall close the app, if you are at the main/landing activity(there are other ways as well). If you want to override backbutton behavior, you should be overriding onBackPressed(), which you are doing right, but you should avoid calling super.onBackPressed() (since this gives you the default behavious, i.e. closing the activity OR finish(), with this you're closing the activity yourself. which is what you want to avoid.
Hope it helps.
#Override
public void onBackPressed() {
if (mSlidingDrawer.isOpened()) {
mSlidingDrawer.close()
} else {
Toast.makeText(MyTestApplication.getAppContext(), "Closing application", Toast.LENGTH_SHORT).show();
super.onBackPressed();
}
}
I have a simple activity with a theme set via setTheme(), the theme id is stored in SharedPreferences, I get this data and setTheme() before super.OnCreate() in the main activity. On pressing the menu button I can launch a preferences activity. On updating preferences and pressing the back button to return to the main activity the theme does not update to the new setting. Only closing the app and reopening fixes this.
What's the best way to make the main activity update and reload the theme after the back button is pressed in the preferences activity? I tried putting setTheme() in OnResume but to no avail.
Any help is greatly appreciated,
Thanks Ric
See this page:
According to Dianne Hackborn, Android framework engineer:
You can only set the theme during
creation. To apply a theme, the
entire UI need to be reinflated and
rebuilt from its resources.
If there is no other way, you could do something like this in your activity, after updating the preferences:
Intent i = new Intent(this, YourActivity.class);
startActivity(i);
finish();
It's not too elegant, and I do hope there is a simpler way.
and setTheme() before super.OnCreate() in the main activity
You shouldn't ever put any code before super.onCreate() or super.onResume(), all your code should be placed after these calls. Maybe this is the problem.
register onsharedpreferencechange listener in your activity
Here is the way I did it:
I have an app that has multiple themes to choose from on a page. Normally, when a theme is selected and then the back button is pressed, the theme reverts back to the previous one. This is an issue.
I used the #Override trick for onBackPressed() to do the trick. Following is the code (I also modified the code for the first activity in the stack [my Navigation Drawer]).
#Override
public void onBackPressed()
{
Intent intent1 = new Intent(this, NavigationActivity.class);
startActivity(intent1);
super.onBackPressed(); // optional depending on your needs
}
That code in the Theme Switch activity made it so the normal back button code wasn't called to destroy the current activity and revert to the old theme. It just passes to the previous activity that the user was on, which is my NavigationActivity. Customize this how you will.
Another thing to note is that the back button can still plague you even after this, because once it passes me to NavigationActivity, if I press the back button again the theme is reverted. I called the same method as before, but I took out the super.onBackPressed(); statement which is what caused the reverting. This is what it looks like:
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
}
I hope this does the trick for you!
If you use Navigation component please try as below mentioned. It is not required to call intent or finishActivity.
override fun onBackPressed() {
when (navController.currentDestination?.id){
R.id.settingsFragment -> super.onSupportNavigateUp()
else -> super.onBackPressed()
}
}
super.onSupportNavigateUp() will be solved your back navigation problem.