0

I added a Toolbar to my Activity with back arrow like this:

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);        
setSupportActionBar(myToolbar);
//add back arrow - but it doesn't go back, nothing happens when I click it
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

But when I click the back arrow, it doesn't go back to previous page

DawidJ
  • 1,245
  • 12
  • 19
pileup
  • 1
  • 2
  • 18
  • 45
  • I think this link can help you [link](https://stackoverflow.com/questions/36457564/display-back-button-of-action-bar-is-not-going-back-in-android/36457747) – Protiuc Andrei Jan 06 '19 at 17:31

3 Answers3

3

add this lines:

@Override
public boolean onSupportNavigateUp() {
    onBackPressed();
    return true;
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish(); // or your code
}
Guy4444
  • 1,411
  • 13
  • 15
  • why not just `finish()` in `onSupportNavigateUp()`? – Joozd Aug 25 '20 at 10:08
  • Very good question. This is because the nav button will do what the back button is supposed to do - So if you perform operations on the back button, you will not have to perform them again (code duplication prevention) – Guy4444 Aug 27 '20 at 19:30
1

You need to override onCreateOptionsMenu() and onOptionsItemSelected() just like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.your_id, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Don't forget to replace R.menu.your_id with your id as name suggest.

DawidJ
  • 1,245
  • 12
  • 19
0

With suggested answers you might want to add parentActivity in your Android manifest.xml

<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" >
    <!-- The meta-data element is needed for versions lower than 4.1 -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

Docs: Android developers

Shahid Kamal
  • 380
  • 2
  • 14