0
votes

I have a customized action bar, i want to add navigation drawer icon on Main Activity by clicking it drawer will open/close and on other activities i want a back arrow, clicking it i go back on parent activity. i have done this for drawer icon and it works,

toolbar.setNavigationIcon(R.drawable.ic_menu_black_24dp);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

and for back arrow i have tried this

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

but only one thing works at a time, how both can work?

1

1 Answers

0
votes

In other activities (where you want back arrow), you should define parentActivityName in AndroidManifest.xml file to define which activity should be navigated when back arrow is pressed.

<activity
        android:name=".activities.ArticleDetailActivity"
        android:parentActivityName=".activities.ArticlesActivity"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.NoActionBar">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.activities.ArticlesActivity" />
</activity>

In this activity java code, you should write following code in onCreate callback method.

ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
}

And in onOptionsItemSelected callback method of that activity, you will also need the following code to return back to previous activity.

public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                onBackPressed();
                return true;
        }

        return super.onOptionsItemSelected(item);
}