无法通过ID获取菜单项

时间:2016-01-31 15:54:45

标签: android menu

所以在我的应用程序中,我的main_menu中有一个微调器和一个搜索视图:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/spinner1"
    android:title="Search for:"
    android:actionLayout="@layout/spin_number"
    app:showAsAction="always"/>
<item
    android:id="@+id/search"
    android:title="search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

和我的spin_number布局:

<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

以下是我尝试访问微调器的代码:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_menu, menu);
    final SearchView searchView = (SearchView)MenuItemCompat.getActionView(menu.findItem(R.id.search));
    final Spinner spinner1 = (Spinner)MenuItemCompat.getActionView(menu.findItem(R.id.spinner1));
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.country_arrays, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
    searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

我在Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference行上收到spinner1.setAdapter错误。但是,searchview不为null。我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

替换main_menu.xml中的以下内容

android:actionLayout="@layout/spin_number"

app:actionLayout="@layout/spin_number"

Reference