masterphp
masterphp

Reputation: 83

How to create a Back Button in Material Design

I cannot find a tutorial about adding this button in the Action bar in Material Design.

example image

How can I add this into the action bar on Lollipop?

Upvotes: 8

Views: 18585

Answers (5)

Tomer Shemesh
Tomer Shemesh

Reputation: 13345

try this

in on create:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

in your activity class (assuming you want to close this activity)

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

Upvotes: 19

Narendra Baratam
Narendra Baratam

Reputation: 828

getSupportActionBar().setDisplayHomeAsUpEnabled(true); may produce nullpointer exception, onCreate() should be like this.

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setupActionBar();
}

/**
 * Set up the {@link android.app.ActionBar}, if the API is available.
 */
private void setupActionBar() {
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        // Show the Up button in the action bar.
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
}

Upvotes: 2

hash
hash

Reputation: 5406

in your onCreate add these lines

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

for back navigation you have to define back navigation actiity on your AndroidMnifest.xml

<activity 
android:name=".CurrentActivity" 
android:label="@string/app_name"
android:parentActivityName=".BackActivity">
</activity>

Upvotes: 3

Harin
Harin

Reputation: 2423

Material Design Tutorial This will give you brief idea how to implement material app.

If you are using ActionBarActivity with AppCompat Theme use:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Also you may have to call setHomeButtonEnabled(true) in same manner. It will look like this:

enter image description here

Upvotes: 13

SilentKnight
SilentKnight

Reputation: 14021


First, you have to use Theme of Material Design, and the Theme supports ActionBar, like Theme.AppCompat.Light, Theme.AppCompat.Light.DarkActionBar.
Second, call ActionBar.setDisplayHomeAsUpEnabled(true); or ToolBar.setDisplayHomeAsUpEnabled(true);, then the Return icon would show.

Upvotes: 1

Related Questions