Issue
I've been researching all day/night for a solution, but it seems there are lots of options to go from an Activity
to a Fragment
, but none are working for me on S.O. In practice, I am in an Activity
, and I want to use my app logo in the ActionBar
to click it and then return to a Fragment
. This Fragment
is the "parent class" of my Activity
, meaning there was a button in the Fragment
I clicked that took me to my Activity
.
But I can't get all the code snippets I've seen to work.
I have put this in my onCreate()
of my Activity
:
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
I also included this in my onOptionsItemSelected()
method of my Activity
:
// Handle action bar actions click
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
return true;
default:
return super.onOptionsItemSelected(item);
}
The result is that I see a "back button" carat (as shown below), but when I click it nothing happens. I'm supposed to go back to the Fragment
I came from. FYI, my Fragment
class actually extends Fragment
(not FragmentActivity
). My Activity
extends ActionBarActivity
, so I am looking for an answer that will work for Android 4.0+. Also, my Fragment
does not need the same instance (necessarily) when it is returned to. It only has buttons on there, so a new instance is fine, if it gets created, upon returning.
Thanks for your help!!
Solution
One small line was needed: finish()
. Since the FragmentManager
pops off one item in its backstack, by using fm.popBackStack();
, it still needs some sort of action to go to the previous fragment. Adding finish()
enabled the current Activity
to end. The line in context:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The rest of the code I had above was correct and is needed too, to make it all work. Now, I am able to navigate to my NavigationDrawer
fragment, click a button there to go to an Activity
, then press the navigation UP caret to return to my Fragment
at anytime. This was tested successfully on a Samsung Galaxy5 phone.
One thing that you do not read about in the Navigating Up with the App Icon section of the ActionBar Android doc is that since you are using a fragment to return to, you cannot use their <meta-data>
tag instruction to specify the parent activity in the manifest file, because you are not returning to an Activity
! But rather a Fragment
. So a workaround had to be achieved by using FragmentManager
.
Answered By - Azurespot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.