尝试将SearchView添加到我的appcompat活动时出现Nullpointerexception

时间:2018-06-03 12:43:41

标签: android nullpointerexception android-actionbar searchview appcompatactivity

尝试将SearchView添加到我的appcompat活动时,我收到了Nullpointerexception。我已经通过this answer但无法解决它。

这是我的

menu_main.xml

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.menu_main, menu);

    mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
    mSearchView.setIconifiedByDefault(true);

onCreateOptionsMenu

mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();

我也尝试过:

class Customer < ApplicationRecord
  has_many :customer_conflicts
  has_many: conflicts, through: :customer_conflicts
end

获得以下异常:

  

java.lang.NullPointerException:尝试调用虚方法   “无效   android.support.v7.widget.SearchView.setIconifiedByDefault(布尔值)”   在空对象引用上

2 个答案:

答案 0 :(得分:1)

试试这段代码:

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            super.onCreateOptionsMenu(menu);
            getMenuInflater().inflate(R.menu.menu_main, menu);

            searchView = new SearchView(this.getSupportActionBar().getThemedContext());
            searchView.setSearchableInfo(searchManager.
                        getSearchableInfo(getComponentName()));

            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

             @Override
             public boolean onQueryTextSubmit(String query) {
                 // collapse the view ?
                 //menu.findItem(R.id.menu_search).collapseActionView();
                 Log.e("queryText",query);
                 return false;
             }

             @Override
             public boolean onQueryTextChange(String newText) {
                 // search goes here !!
                 // listAdapter.getFilter().filter(query);
                 Log.e("queryText",newText);
                return false;
             }


            });

        }

答案 1 :(得分:0)

试试这个。它正在工作

<强> menu.xml文件

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    android:iconifiedByDefault="false"
    android:title="Search"
    app:actionViewClass="android.support.v7.widget.SearchView"
    app:showAsAction="always" />

Java代码:

 @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sol_menu, menu);
    MenuItem menuItem = menu.findItem(R.id.action_search);
    SearchView searchView = (SearchView) menuItem.getActionView();
    searchView.setIconified(false);
    super.onCreateOptionsMenu(menu);
}