【问题标题】:How to override previous menu in toolbar while switching from one activity to another?从一个活动切换到另一个活动时如何覆盖工具栏中的上一个菜单?
【发布时间】:2016-05-16 11:09:38
【问题描述】:

我在工具栏中使用搜索菜单项,在从一个活动切换到另一个活动时,单击搜索按钮会给出输出 Log.d(TAG, "Default" ),而不是 Log.d(TAG, "Search button Pressed" );

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // The action bar home/up action should open or close the drawer.
    // ActionBarDrawerToggle will take care of this.

    Log.d(TAG, "menu Item id = " + item.getItemId() );

    Log.d(TAG, "search id = " + R.id.search_emp);

    // Handle action buttons
    switch (item.getItemId()) {
        case R.id.search_emp:

            Log.d(TAG, "Search button Pressed" );


            return true;

        case android.R.id.home:
            this.finish();
            return true;

        default:

            Log.d(TAG, "Default" );
            return super.onOptionsItemSelected(item);
    }


}

search_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/search_emp"
    android:title="@android:string/search_go"
    android:icon="@drawable/ic_action_search"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:visible="true"/>

回应

05-16 16:34:11.511 3882-3882/? D/SearchListActivity: menu Item id = 2131493212
05-16 16:34:11.511 3882-3882/? D/SearchListActivity: search id = 2131493213

即使我在我的新活动中声明了一个新菜单,它仍然会显示以前的菜单。并且 onclick 也执行之前活动中声明的相同方法。

我卡在这里,请帮帮我。谢谢。

【问题讨论】:

    标签: android android-xml android-menu


    【解决方案1】:

    您可以在为新方法充气之前调用方法 menu.clear()。如果您按下返回按钮 - 前一个活动(或)片段的菜单将被恢复。

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.your_menu, menu);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多