Reputation: 559
My android application has the following activity flow
Listing -> Buy -> Sell From the listing when an item is clicked/selected an id is passed to buy to pull the relevant data from the server. If a user owns a certain item there will be a sell option as well from the buy screen (which doubles as an overview of said item).
The problem I am facing is that when you are on the sell screen and press the android back button you are taken back to the buy screen in it's original state, however when you click the back arrow (up) from the activity in the toolbar, it seems that it is actually trying to launch a new activity and throws an exception (since the activity cannot know what the id was). The buy activity is listed as a parent to the sell activity in the manifest.
I need to somehow make the up button to act the same as the back button on this particular activity, or at least pass the id back somehow.
Any suggestions would be appreciated.
Upvotes: 2
Views: 304
Reputation: 21736
In your Activity, onOptionsItemSelected()
method get the clicked item id
, if the id
is android.R.id.home
then just finish()
current activity.
Try this:
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Upvotes: 1
Reputation: 38223
If you're using an ActionBar
(either platform or AppCompat) override the following method in the activity from which you wish to go back.
@Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
final int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
This should be safe to use in a simple navigation hierarchy such as yours.
Upvotes: 3
Reputation: 366
Just yesterday i did this for my app. This is what I did:
In manifest
file I removed
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.app.MainActivity" />
that was part of my DetailsActivity
.
In the DetailsActivity
I added this line to onCreate
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and in onOptionsItemSelected()
method I added these lines
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
Not sure if it is the best way to handle this but oh well it works :)
Upvotes: 2