VinceMedi
VinceMedi

Reputation: 210

How can i catch the back event from a menu?

I don't know how to catch the back event from a menu :

enter image description here

I mean i want to catch the event when press the back button on the top left of the screen.

Here the xml file of the menu :

        <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:theme="@style/ActionModeMenu">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <CheckBox
            android:id="@+id/context_menu_select_tweet_checkbox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="2dp"
            android:onClick="onSelectAllTweet" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:theme="@style/ActionModeMenuSubtitle"
            android:text="@string/menu_tweet_select_all_text"/>

    </LinearLayout>

    <TextView
        android:id="@+id/context_menu_select_tweet_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:paddingLeft="10dp"
        android:theme="@style/ActionModeMenuTitle"/>

   </LinearLayout>

Thanks !

Upvotes: 2

Views: 126

Answers (2)

Abhishek Singh
Abhishek Singh

Reputation: 9188

Use android.R.id.home to Navigation back button

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        //Navigation Back Pressed
    }
    return super.onOptionsItemSelected(item);
}

Upvotes: 2

John Joe
John Joe

Reputation: 12803

Use android.R.id.home

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

In case you want to change the image of the back arrow, you can write this in OnCreate method

final ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.mipmap.back_to); // change the image

Upvotes: 4

Related Questions