永远不会调用onOptionsItemSelected

时间:2015-04-29 16:18:00

标签: android android-studio

我跟着这个tutorial,我正在写一个简单的Activity

...

更新:在我的提示之后我已经编辑了我的应用,但是当我从弹出菜单中选择一个项目时,仍然没有调用方法onOptionsItemSelected()。当用户单击操作栏中的项目时,弹出菜单会膨胀。

活动:

public class Map extends AppCompatActivity implements
    GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerClickListener,
    GoogleMap.OnMapClickListener, OnMapReadyCallback,
    ResourceState.OnResourceStateChangeListener {

...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Map.menu = menu;
    getMenuInflater().inflate(R.menu.map_menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

        ...

        case R.id.menu_item_map_type:
            // Here I show the popup
            PopupMenu popup = new PopupMenu(this, findViewById(R.id.menu_item_map_type));
            popup.getMenuInflater().inflate(R.menu.map_popup, popup.getMenu());
            popup.show();
            break;

        case R.id.menu_item_satellite:
            // here the method onOptionsItemSelected is not directly called
            break;

        case R.id.menu_item_street:
            // here the method onOptionsItemSelected is not directly called
            break;
    }

    return super.onOptionsItemSelected(item);
}

public void callOnOptionsItemSelected(MenuItem item) {
    onOptionsItemSelected(item);
}

...

}

主菜单:

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" >

    <item android:id="@+id/menu_item_send"
          android:icon="@drawable/ic_send"
          android:title="send"
          app:showAsAction="ifRoom"/>

    <item android:id="@+id/menu_item_location"
          android:icon="@drawable/ic_location_on"
          android:title="my position"
          app:showAsAction="ifRoom"/>

    <item android:id="@+id/menu_item_map_type"
          android:icon="@drawable/ic_map"
          android:title="map view"
          app:showAsAction="ifRoom"/>

</menu>

弹出菜单:

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >

    <item
        android:id="@+id/menu_item_satellite"
        android:title="satellite"
        android:checkable="true"
        android:onClick="callOnOptionsItemSelected"/>

    <item
        android:id="@+id/menu_item_street"
        android:title="street"
        android:checkable="true"
        android:onClick="callOnOptionsItemSelected" />

</menu>

我的临时解决方案是定义方法callOnOptionsItemSelected(),它调用方法onOptionsItemSelected()。顺便说一下,我想知道我错过了什么。

(与弹出窗口相关的另一个问题是类setChecked()的方法MenuItem无效。)

1 个答案:

答案 0 :(得分:-2)

我不知道你为什么要添加

android:id="@+id/layout_map_popup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" 

在您的menu.xml文件中