Alex
Alex

Reputation: 44305

How to make the 'back-arrow' work in the toolbar?

I have the following part of the xml code that defines my toolbar:

<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:columnCount="5"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:useDefaultMargins="true"
    android:alignmentMode="alignBounds"
    android:columnOrderPreserved="false">

    <android.support.v7.widget.Toolbar android:id="@+id/toolbar_setting"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"/>

    ... // other code here

and the code in the SettingsActivity (derived from AppCompatActivity) is as follows:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings);

    // Set toolbar, allow going back.
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_setting);
    toolbar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("Settings");

When compiling and running the code I see a toolbar as follows:

enter image description here

but a click on the left-arrow does not get me back to the previous menu. What am I missing here?

Upvotes: 1

Views: 112

Answers (3)

Abdul Fatir
Abdul Fatir

Reputation: 6357

As you need to go one level up, make the following changes in your AndroidManifest.xml.

<activity
        android:name=".CurrentActivity"
        android:parentActivityName=".OneLevelUpActivity">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".OneLevelUpActivity" />
</activity>  

In onCreate() add toolbar.setHomeButtonEnabled(true);

The <meta-data> is to support earlier API versions (<API level 16).

Upvotes: 1

Yasin Ka&#231;maz
Yasin Ka&#231;maz

Reputation: 6663

You can access that little arrow by android.R.id.home :

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

    return(super.onOptionsItemSelected(item));
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

If you try this code , when you click arrow, it will act like your back button pressed.

Upvotes: 2

tyczj
tyczj

Reputation: 73741

in onOptionsItemSelected you need to listen for the click then do something

case android.R.id.home:
     // do something with the click
     break;

Upvotes: 1

Related Questions