Android toolbar: how to go back to previous activity if back arrow is pressed

I have an activity called Place

I am returning to Placeactivity from my previous action called City.

I added a back button to the toolbar Placewith the following code:

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true)

I want the back button to return to Cityactivity

But for the operation City, some parameters are needed, which must be passed to it.

So, how to tell the "Back" button to go to the "City Activity", without having to pass parameters to it.

+4
source share
5 answers

backButton finish();, Activity .

+2

. finish ()

, . finish(), . .

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) // Press Back Icon
    {
        finish();
    }

    return super.onOptionsItemSelected(item);
}
+14

AndroidManifest.xml android: parentActivityName , . java

 getActionBar().setDisplayHomeAsUpEnabled(true);

. .

<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
    android:name="com.example.myfirstapp.MainActivity" ...>
    ...
</activity>
<!-- A child of the main activity -->
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>
</application>
+7
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
+3

:

Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true)

.

In the manifest:

<activity
    android:name="Your Second Activity"
    android:parentActivityName="Your First Activity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="Your First Activity" />
</activity>

And finally use:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) 
{
   NavUtils.navigateUpFromSameTask(this);
}

return super.onOptionsItemSelected(item);
}
0
source

All Articles