I have 3 activities:
MainActivity (start activity with grid view)
FragmentActivity (full screen image slider accessed from grid view)
InfoActivity (blank activity opened from menu in either Main or Fragment)
When I go from MainActivity to InfoActivity:
startActivity(new Intent(MainActivity.this, InfoActivity.class));
and press the "up" button I get back to main activity.
When I go from FragmentActivity to InfoActivity
startActivity(new Intent(this, InfoActivity.class));
and press the "up" I STILL get back to MainActivity.
I know it's because my MainActivity is the parent of Info.
But how do I make the "up" behave like the "back" button, so that I can go from InfoActivity to FragmentActivity?
Any help will be much appreciated!
You have to override onOptionsItemSelected in the InfoActivity class to intercept the "up" button and call onBackPressed from there. Like so:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
The answer from #Firoze Rakib will work but I would like to provide you better understanding of the problem and solution advised by Google.
First of all you most probably have defined parent in your AndroidManifest.xml, you should remove it since your InfoActivity can have different parents.
Secondly, there is a small difference between BACK BUTTON(which is programatically called in #Firoze answer) and UP BUTTON. First one simply destroy current activity and show activity that was previously shown, theoretically it does not have to be any of your parents. The UP BUTTON starts new instance of the parent Activity and clear the activity stack in the current task.
If this difference matters for you then you should follow instructions from Android Developers page. Take a look at second point that starts with this sentence:
Or, override getSupportParentActivityIntent() and
onCreateSupportNavigateUpTaskStack() in your activity.
how do i make the "up" behave like the "back" button...
I believe another answer has the technical details if you are determined to do this (which you should not).
The purpose of my answer is to point out that making up behave like back will confuse users by violating the Android design guidelines.
Up navigation is an alternative to using the back key with a different purpose: it gives the user a way to navigate back to the top of an app when they are "lost" deep in a hierarchy and they might have to press the back key many times to escape. In this situation some users will panic and start mashing the back key, and up nav is meant to give them an alternative.
Try this
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null )
if( && item.getItemId() == android.R.id.home) {
// your code
return true;
}
return super.onOptionsItemSelected(item);
}
Related
I have not seen a specific answer to this question so please do flag this as a duplicate if you can find the duplicate.
I am wondering how does one make the back button of the Action Bar button act as the system back button. So when an action bar is displayed and there is the application icon in the top left with the back arrow, how does one make that act as the system (hardware sometimes) back button?
Here is an example of the button I am talking about.
So in order to do this you will need to on your activitys UI setup call these.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
and then if you do not want text, like that example you need to call
getSupportActionBar().setDisplayShowTitleEnabled(false);
Then in your activity you need to create a method that looks like this.
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int theId = item.getItemId();
if (theId == android.R.id.home) {
callCleanupActivityMethod();
finish();
}
return true;
}
That is a callback listener that is immediately put on the activity when an action bar has been put on the activity. That function then grabs the id of the item that was clicked, checks to see if it was the home button, then you need to clean any objects or processes that need to be stopped then call finish() which will make the activity finish. Finally return true.
When looking at the comments you can probably see that a member suggested just calling onBackPressed, that may work for some applications but not all hence the call to finish. I do recommend trying it first though.
Cheers
On my apps home page I have an option to add items to a ListView using adapter.add(string). I also have another Activity that my app goes to using startActivity(intent). When I am in that second Activity and I press the back button all of the data that was added to the list is still there, however when I press the icon at the top left all the data is gone. Is there a way to make it so that the button for the icon preserves the data in my list. I think I should note that I don't want the data to be preserved when the app is closed, only when navigating through the open app.
This is my current method that handles the home button action:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
A quick solution would be to call onBackPressed() instead of NavUtils.navigateUpFromSameTask(this). This, however, isn't recommended and you should try to implement proper navigation logic. Take a look at the answers to this question as well as these tips.
I have Activity A (Main) and Activity B.
Fact: Activity A has: android:launchMode="singleInstance"
Usual scenario is:
User launches application > Activity A.
User clicks an item > Activity B
3.A. If user clicks on back/up buttons > Back to A (without calling finish() on B)
User clicks the SAME item as before > Forth to B.
At this point he can go back and forth without new instances. It's all in the stack and it doesn't recreate activities. (All right!)
3.B. If user clicks Home, then goes to task manager and brings the app to front > Activity B (all good, so far)
If user clicks UP button, it goes to TASK MANAGER, and I want it to go to Activity A (back button is expected to work this way, so let's focus on UP button).
Here's the implementation I have in Activity B for BACK and UP buttons.
#Override
public void onBackPressed() {
moveTaskToBack(true);
// I don't want to finish() the activity, so the user can reclick the same
// item without reloading the whole activity again (webview slow when parsing html).
return;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
moveTaskToBack(true);
// I don't want to finish() the activity... idem.
// I need to implement here the bring Activity A to front
break;
}
}
So, what I want is: to "Go Back" to Activity A keeping the same idea of using the stack to reload Activity B if needed, without using Intents (unless it calls activity to front, without adding items to the stack.)
Let me know if I explained myself clearly and if you need more info.
UPDATE:
I've found this at: http://developer.android.com/training/implementing-navigation/ancestral.html
This is how I adapted it.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = new Intent(this, Activity_A.class);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.create(this).addNextIntentWithParentStack(upIntent).startActivities();
} else {
moveTaskToBack(true); // I want it this way. Don't worry.
}
break;
}
}
But the method NavUtils.shouldUpRecreateTask is ALWAYS returning false.
I did the http://developer.android.com/training/implementing-navigation/ancestral.html#SpecifyParent part, so that's not the issue.
My problem is that I want to recognize if Activity A exists in the stack, for when i.e. the app is launched from the task manager.
How can I achieve this?
Thanks.
moveTaskToBack moves the entire task to the background. it doesn't finish the activity.
in order to have full control of activities, you have some possible solutions:
create your own global manager for the activities, monitor each of them through all of their lifecycle and decide what to do on each event.
you could also finish each activity as soon as you go from it, and put "it" (just its name or something) in a stack and restore its state when you come back to it.
use fragments instead, and manage them all on a single activity. be warned of configurations changes though.
I am developing an application which starts from LoginPage. When user Login then he moves to Main Screen where grid view for different departments are present.
Every page of application except login page has a Footer which have different Icons like Home, logout, etc.
I want to add conditional back functionality using mobile back button. Some conditions are as follow:
1) LoginPage ---> Main Screen ---> On back user should log out and go to Login Page
2) Main Screen --> any department ---> Any Sub deprtment --> If user press Back button then go to back in same order
3) User is any where in application ---> If press home button from Footer ---> Comes to Main Screen --> No back functioality to go on previous page, It should follow condition 1.
4) If User on Login Page then he will exit from application on pressing Back Button
5) If User on main Screen then user should logout and go to Login Page on preseeing Back Button
I have tried with "noHistory=true" in Manifest and with Intent flags in Activity file.
Can any body suggest me best way to solved out it.
shouldn't be a problem, all you have to do is override the onBack function and add the logout process.
not a problem, the normal behavior of back buttons is exactly that.
DO NOT DO THIS!!! BAD BEHAVIOR.
normal behavior of back button.
that was step one.
this is used for exit from application on back press.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
System.exit(0);
}
return super.onKeyDown(keyCode, event);
}
if u want only back then remove System.exit(0) from above code .
By using this you can manage your all condition which one you want.
Use a stack globally to save screens order. Stack must be available in application level. And get the screen order when you click on back button. Write switch case for screen order and start that activity. that's it.
for example.
crate a class class MyStack{
//here declare a static stack
//create setter,getter method for assinging values to stack
}
when starting new activity assing screen value in stack with setter method
if you are starting a activity from main screen assign 1 into stack, you are starting sub screen assign 2 into stack.
when click on back get that value
switch(value){
case 1: //start mainscreen break;
case 2: //start sub screen break;
}
With what I understand, you cannot override the functionality of home button. By default, it minimizes your app with its current state, by calling onPause(). When you open the app again, onResume() is called and starts the app from where it was paused. As far as your back button functionality is concerned, most of the above answers are fine.
Try,
#Override
public void onBackPressed()
{
finish(); //finishes the current activity and doesnt save in stock
Intent i = new Intent(CurrentActivity.this, Login.class);
i.addflags(Intent.flag_activity_no_history);
startActivity(i);
}
Try this to trap events on the back button
public boolean onKeyDown(int keyCode, KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_BACK) {
Intent Act2Intent = new Intent(thisActivity, Activity2.class);
startActivity(Act2Intent);
finish();
return true;
}
return false;
}
on each activity implement
OnBackPress().
Override it and add the functionality you want like logging out, clearing history stack and start new(previous) activity.
I think simplest approach may be to override back button in your "Main Screen" activity so that when back button is pressed you can do :
1. Executing log out logic:
2. Explicitly call your Login Page
This may give the behavior you are looking for.
On how to override back button, you can refer to this link:
http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html
Hope this helps!
I have some strange effects in my Android App.
I use a TabHoster with TabGroupActivities for each Tab. Works pretty good except the behaviour of the Back Button.
An Activity is launched and responds to the Back button. Then I start a Child Activity with a ViewSwitcher. When i hit the Back Button on View A Activity is dismissed as Expected. But it gets through the onBackPressed() of my Activity.
When i hit the Back Button on View B (detailView==true) the Method is not even Called. Instead of that the onBackPressed() of the TabGroupActivity is Called and I am not able to switch back to the first View.
#Override
public void onBackPressed() {
if (detailView == true){
vf.showPrevious();
detailView = false;
}
else {
super.onBackPressed();
}
return;
}
Can Anybody explain this and/or tell me how to switch between Views in an Activity in an ActivityGroup?
Few Days later i came to the Conclusion that it is FOR MY CASE the easiest solution to throw away the ViewSwitching stuff and transfer them to seperate Activities.
Sebastian Olsson is surely right with the fragments but it would be more effort for my specific App to rebuild everything to fragments.