Up Navigation not working as expected - android

I have three activites, lets call them A, B, and C.
I initially have activity A passing data with intent and calling activity B to open, displaying the data passed from activity A.
Now the issue is when I open activity C from activity B, and use the up navigation that I set up by setting activity B as the parent of Activity C in manifest, none of the data is displayed from Activity A in Activity B. If i simply make a button and call finish(); on the button instead, and not use the up navigation, the activity still contains all data from activity A just how I want it in Activity B.
I'm assuming this has to do with the lifecycle of using up navigation? I even tried using the intent from activity B to C by passing data, and then onResult have it return back to activity B, but it seems the onActivityResult is never called when up navigation is clicked. Any ideas? Maybe I can override this up navigation to just call finish(), like my button does, and nothing more?

Assuming you already have the parent activities defined at the Manifest, make sure you override the following methods:
#Override
public void onCreate(Bundle savedInstanceState) {
// You code here
getActionBar().setDisplayHomeAsUpEnabled(true);
// or getSupportActionBar().setDisplayHomeAsUpEnabled(true) if using support actionbar, i.e., for targets < 3.0;
}
Now you will be able to catch the action of the "Up" button with the Id android.R.id.home.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}

Related

How to navigate from fragment in one activity to fragment in another activity?

I want to add back navigation to toolbar. I need to get from a fragment in an activity to a specific fragment in another activity.
It looks a little like this, where every orange line means navigating to a new activity or fragment:
How do I move from fragment B to fragment A from OtherActivity?
Consider these steps:
From Activity 1 holding Fragment A , you want to directly load Fragment B in Activity 2.
Now, I am thinking first, then you press a button in Fragment A, you can directly go to Activity B.
Then it means, you can simply load Fragment B as soon as you arrive in Activity 2.
Since you are dealing with back navigation (I believe you mean the upNavigation?), you can override the following:
But watch clearly, because if you need to load an exact fragment in Activity 2, you need to know somehow:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("frag", "fragmentB");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
As you can see, when you click the back arrow on the toolbar, we pass a value through our intent to identity which fragment we want to load.
Next, in your Activity2, simply get the intent extra and do a switch or an if statement:
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
String frag = intent.getExtras().getString("frag");
switch(frag){
case "fragmentB":
//here you can set Fragment B to your activity as usual;
fragmentManager.beginTransaction().replace(R.id.container_body, new FragmentB()).commit();
break;
}
}
From here, you should have your Fragment B showing in Activity 2.
Now you can handle the same thing while inside Activity 2 to decide where to go when a user clicks the back home arrow!
I hope this helps you get an idea.
Note: I thought about the interface approach and realized it is not necessary since this can be done easily with this approach!
To navigate from one Activity to another Activity's Fragment, with Kotlin version 1.4.0 and, for example, calling a click listener on a button it works so:
binding.yourButton.setOnClickListener {
supportFragmentManager.beginTransaction().replace(R.id.yourLayout, NameOfYourFragment()).commit()
}
Use this code to change your fragment
fragmentManager.beginTransaction().replace(R.id.container_body, new FragmentC()).commit();
and to show navigation on custom toolbar add
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true)
((AppCompatActivity)getActivity()).getSupportActionBar().setHomeButtonEnabled(true);

Activity B: Go back to Activity A on Actionbar calls A.onCreate(). The Back button does not

I have activity AActivity which calls Activity BActivity.
In the AndroidManifest I specify B as follows:
<activity android:name=".main.BActivity"
android:parentActivityName=".main.AActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".main.AActivity" />
</activity>
If I'm in Activity B and click on the phone's Back-Button, then I go back to Activity A without calling A.onCreate(); again - that's how I want it to be. But If I'm in Activity B and click the ActionBar's Back button on the top left, then I go back to Activity A again, but A.onCreate(); is called. How can I use the backbutton of the top of the Activity to behave in the manner the phone's back button does, i.e. not calling StartingActivity.onCreate() ?
Btw: Activity A and B are extending from AppCompatActivity.
Inside your OnClick(View view) function call finish().
Related guide
you can use android:launchMode="singleTop" in manifest inside activity A. read this following link for more details return parent activity correctly
Call finish() onBackPressed() and onOptionsItemSelected() when id == android.R.id.home
#Override
public void onBackPressed(){
if(EcologDriverAIDApplication.DEBUG){
Log.i(TAG, "onBackPressed");
}
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//Back button pressed
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
How can I use the backbutton of the top of the Activity to behave in the manner the phone's back button does, i.e. not calling StartingActivity.onCreate() ?
//declare android:onClick="backButtonPressed" in your xml in the back button layout
public void backButtonPressed(View view) {
onBackPressed();
}
Why it should work:
When you press the bottom back button of android, onBackPressed() is called. As you have said, the bottom back button tap works the way you want it to. Therefore, just call it from your click listener of the back button at the action bar

Android activity to a fragment control transfer

I am creating an android application with three tabs using PageSlidingtabStrip as a library to create a swipe view.And it has three fragments.Each fragments has a list view.When the item of the listview is clicked it opens an activity and display the details.
The problem is how can i come back to the fragment in the main screen using back button in actionbar in the activity
And how can i go to the corresponding Fragment(Tab)
Try something like this :
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(YourCurrentClass.this , ClassThatYouWantToGo.class);
startActivity(intent)
}
Or actually like #TommyTopas said, you can just Override onBackPressed and put this.finish();.
EDIT
As I've understood you want to use a button on your AcitonBar, then you have tod o something like this :
First set the HomeButton enabled doing :
getActionBar().setDisplayHomeAsUpEnabled(true); Then Override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// or onBackPressed();
this.finish()
}
return true;
}
As I understand, when you return to the "Tab" Activity, you want to display the same tab in which the list item had been clicked. What you can do is, when a list item in any tab is clicked, save the tab number in onSavedInstanceState(), and when the Activity is recreated, then set the previously selected tab (if one was selected previously). You will get the savedInstanceState that you saved in onSavedInstanceState() back in the onCreate() of the same Activity.
You can provide an Up navigation by writing getActionBar().setDisplayHomeAsUpEnabled(true); and then in the onOptionsItemSelected method in the activity, if the item's id is android.R.id.home call the activity's method onBackPressed(); which will close your current activity and come back to your fragment

Pressing back button calls onCreate (Android)

Activity A starts Activity B. In Activity B, I have this method:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this, new Intent(this,
ArticleListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
When I press that home button, it takes me to Activity A as it should. However, onCreate is being called again. I do not want this behavior.
I'm guessing its because this implementation uses new Intent to previous item in the navigation stack. This is just code I got from Eclipse when creating the double pane project though. I looked around on stack overflow, and though it seems that using an Intent to go back is causing this behavior, I do not understand why Google would provide this in a default template.
How should I make this call differently so that onCreate is not called again when going back to Activity A?
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
just finish current activity it will take you on previous activity
if your previous activity is activity A then just use finish(); method instead of creating object of intent
As pointed out by #Rajesh you need to call onBackPressed().
Your code detects the home button press and creates a new ArticleListActivity class.However, you don't want to create a new class you only want to go back to your already created class/activity. so use onBackPressed() instead.
You can try to set the launch mode in the manifest, because the parent activity can be popped off the stack.
android:launchMode="singleTop"
In this way, the onCreate() is not called again.
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}

How can I programmatically set a parent activity in android [duplicate]

So at the moment I have an activity that can be reached from two different activities, the problem is that I can only set one activity as the parent activity in the manifest XML file. Obviously this is bad UX/UI design because the activity may send the user back to the wrong activity they were at previously and so I'm trying to dynamically set which activity is the parent activity.
The trouble is I'm not quite sure how to go about this, whether in code or XML so any pointers are appreciated. :)
For future readers here's an example of how to actually implement the official/proper solution as per the developer guides (scroll to the paragraph beginning with "This is appropriate when the parent activity may be different...").
Note that this solution assumes you are using the Support Library to implement your ActionBar and that you can at least set a 'default' parent Activity in your manifest XML file to fallback on if the Activity you are backing out of is in a 'task' that doesn't belong to your app (read the linked docs for clarification).
// Override BOTH getSupportParentActivityIntent() AND getParentActivityIntent() because
// if your device is running on API 11+ it will call the native
// getParentActivityIntent() method instead of the support version.
// The docs do **NOT** make this part clear and it is important!
#Override
public Intent getSupportParentActivityIntent() {
return getParentActivityIntentImpl();
}
#Override
public Intent getParentActivityIntent() {
return getParentActivityIntentImpl();
}
private Intent getParentActivityIntentImpl() {
Intent i = null;
// Here you need to do some logic to determine from which Activity you came.
// example: you could pass a variable through your Intent extras and check that.
if (parentIsActivityA) {
i = new Intent(this, ActivityA.class);
// set any flags or extras that you need.
// If you are reusing the previous Activity (i.e. bringing it to the top
// without re-creating a new instance) set these flags:
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
// if you are re-using the parent Activity you may not need to set any extras
i.putExtra("someExtra", "whateverYouNeed");
} else {
i = new Intent(this, ActivityB.class);
// same comments as above
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
i.putExtra("someExtra", "whateverYouNeed");
}
return i;
}
NOTE: If you do not set a default parent Activity in the manifest XML file then you'll also need to implement onCreateSupportNavigateUpTaskStack() since the system will have no idea how to generate a backstack for your task. I have not provided any example for this part.
My thoughts on the finish() type solutions
On my searching for a solution to this problem I came across a few answers that advocate the strategy of overriding onOptionsItemSelected() and intercepting the android.R.id.home button so they could simply finish() the current Activity to return to the previous screen.
In many cases this will achieve the desired behavior, but I just want to point out that this is definitely not the same as a proper UP navigation. If you were navigating to the child Activity through one of the parent Activities, then yes finish() will return you to the proper previous screen, but what if you entered the child Activity through a notification? In that case finish()ing by hitting the UP button would drop you right back onto the home screen or whatever app you were viewing before you hit the notification, when instead it should have sent you to a proper parent Activity within your app.
Like this way you can navigate dynamically to your parent activity:
getActionBar().setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
NOTE: It redirects you to the activity or fragment where you came from, no matter whether it's a parent or not. Clicking on the action bar Up/Home button will just finish the current activity.
There are two concepts in play here 'Up' and 'Back'. 'Back' is the obvious one: take me to where I was just before I came here. Usually you don't need to be concerned with 'Back', as the system will handle it just fine. 'Up' is not so obvious - it's analogous to Zoom Out - from an element to the collection, from a detail to the wider picture.
Which of these fits your use case?
As per comment below: the up button pulls the destination from the android manifest, but it can be customized programmatically.
The method to override is getParentActivityIntent.
Here is my code and works perfectly fine.
#Override
public Intent getParentActivityIntent() {
Intent parentIntent= getIntent();
String className = parentIntent.getStringExtra("ParentClassSource");
Intent newIntent=null;
try {
//you need to define the class with package name
newIntent = new Intent(OnMap.this, Class.forName(className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return newIntent;
}
From the parent activities;
Intent i = new Intent(DataDetailsItem.this, OnMap.class);
i.putExtra("ParentClassSource", "com.package.example.YourParentActivity");
startActivity(i);
To find out how to use Up Navigation properly see this Android Dev Guide.
Note that there is a big flaw in the above Android Dev Guide as the NavUtils functions work differently for ICS(and lower) and JellyBean(and higher). This flaw in NavUtils is explained beautifully here.
Generally, a 'detail' type of activity will have to provide the 'up' navigation if it has nested/related contents. The 'back' navigation is handled by the system so you really don't have to worry about it.
Now for the extra effort to support the 'up' navigation, there are a few ways of doing it:
Activity that has the parent activity defined in the AndroidManifest.
Your Android Manifest
---------------------
<activity
android:name="com.example.app.DetailActivity"
android:parentActivityName="com.example.app.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app.MainActivity" />
</activity>
Your Detail Activity
--------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
This works well if there's only one parent activity meaning if the (DetailActivity) always gets launched from (MainActivity). Otherwise this solution will not work if (DetailActivity) gets launched from different places.
More here: http://developer.android.com/training/implementing-navigation/ancestral.html
(Easier and Recommended) Activity with Fragment and Fragment back-stack:
Your Detail Activity
--------------------
protected void replaceFragment(Bundle fragmentArguments, boolean addToBackStack) {
DetailFragment fragment = new DetailFragment();
fragment.setArguments(fragmentArguments);
// get your fragment manager, native/support
FragmentTransaction tr = fragmentManager.beginTransaction();
tr.replace(containerResId, fragment);
if (addToBackStack) {
tr.addToBackStack(null);
}
tr.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
In this solution, if the user presses 'back', the fragment will be popped from the fragment backstack and the user is taken back to the previous fragment while still remaining in the same activity. If the user presses the 'up', the activity dismisses and the user is lead back to the previous activity (being the parent activity). The key here is to use the Fragment as your UI and the activity as the host of the fragment.
Hope this helps.
You can override the Up button to act like the back button as following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
You will need to keep track of the parent activity. One way to do this is by storing it as an extra in the intent you create to start the child activity). For example, if Activity A starts Activity B, store A's intent in the intent created for B. Then in B's onOptionsItemSelected where you handle the up navigation, retrieve A's intent and start it with the desired intent flags.
The following post has a more complex use-case with a chain of child activites. It explains how you can navigate up to the same or new instance of the parent and finish the intermediate activities while doing so.
Android up navigation for an Activity with multiple parents
Kotlin 2020
My activity launches from different activities so the AndroidManifest only works with 1 parent activity.
You can return to the previous activity like this:
supportActionBar?.setDisplayHomeAsUpEnabled(true)
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId){
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}

Categories

Resources