2

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 !

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
VinceMedi
  • 210
  • 2
  • 8
  • 1
    Possible duplicate of [How to implement the Android ActionBar back button?](https://stackoverflow.com/questions/10108774/how-to-implement-the-android-actionbar-back-button) – Navneet Krishna Oct 26 '17 at 07:25
  • No, my Action bar is displayed only when i long clicked on an item for a multiple selection. – VinceMedi Oct 26 '17 at 07:36

2 Answers2

4

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
John Joe
  • 12,412
  • 16
  • 70
  • 135
2

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);
}
Abhishek Singh
  • 9,008
  • 5
  • 28
  • 53