SearchView片段Android

时间:2017-06-03 21:15:04

标签: java android android-fragments searchview

我有一个片段工具栏,我想为这个工具栏添加searchView

我有这个:

 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    menu.clear();
    getActivity().getMenuInflater().inflate(R.menu.menu_principal, menu);
    MenuItem item = menu.findItem(R.id.buscar);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(item);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            try {
                ArrayList<Producto> listaFiltrada = filter(list,newText);
                adapterProductos.setFilter(listaFiltrada);
            }catch (Exception r) {
                r.printStackTrace();
            }
            return true;
        }
    });

    MenuItemCompat.setOnActionExpandListener(item, new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            adapterProductos.setFilter(list);
            return true;
        }
    });
}

和此项目菜单:

<item android:title="Buscar"
    android:id="@+id/buscar"
    android:icon="@drawable/ic_search_white_24dp"
    app:actionViewClass= "android:support.v7.widget.SearchView"
    app:showAsAction="ifRoom|collapseActionView"
    />

但我有一个空指针......

  

致命的例外:主要                                                                                 流程:jaimeperezpedraza.org.tienda,PID:15971                                                                                 java.lang.NullPointerException:尝试调用虚方法&#39; void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView $ OnQueryTextListener)&#39;在空对象引用上

我认为我没有抓住searchView ......

帮助?

1 个答案:

答案 0 :(得分:2)

NullPointerException归因于searchView为空。这是因为您的XML有app:actionViewClass="android:support.v7.widget.SearchView" - 请注意类名中间的:

应该是android.support.v7.widget.SearchView

<item android:title="Buscar"
  android:id="@+id/buscar"
  android:icon="@drawable/ic_search_white_24dp"
  app:actionViewClass= "android.support.v7.widget.SearchView"
  app:showAsAction="ifRoom|collapseActionView"
  />