检测到操作栏后退按钮的点击 - (单击操作栏后退按钮时OnOptionsItemSelected未调用)

Hus*_*Rad 14 android optionmenu android-actionbar searchview

我有一个包含a的操作栏searchview.当用户单击搜索按钮并折叠搜索视图时,操作栏会在左侧显示后退按钮.

在此输入图像描述

我们如何检测用户何时点击此后退按钮?

编辑

基于答案,我检查了我,OnOptionsItemSelected但它也没有打电话.这是我的代码OnOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (item != null && id == android.R.id.home) {
        if (mNavigationDrawerFragment.isDrawerOpen(Gravity.RIGHT)) {
            mNavigationDrawerFragment.closeDrawer(Gravity.RIGHT);
        } else {
            mNavigationDrawerFragment.openDrawer(Gravity.RIGHT);

        }
        return true;
    }
    if (id == R.id.action_search) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)

小智 12

把它放在onCreateOptionsMenu方法上:

MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.action_search), new MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {

        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {

        //DO SOMETHING WHEN THE SEARCHVIEW IS CLOSING

        return true;
    }
});
Run Code Online (Sandbox Code Playgroud)


mas*_*a98 5

您应该在manifest.xml中添加所需的元数据

喜欢

<activity
        android:name=".Example"
        android:label="@string/Example"
        android:theme="Theme.AppCompat.Light">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".MainActivity" />
    </activity>
Run Code Online (Sandbox Code Playgroud)

并且您的代码应与示例中的类似

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 .......
         getActionBar().setDisplayHomeAsUpEnabled(true);

......
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)