如何在片段中使用getFilter()过滤ListAdapter

时间:2016-03-05 14:37:16

标签: java android android-layout listview android-fragments

我想使用搜索操作栏过滤ListAdapter,这是一个SimpleAdapter。我很难理解如何在我的onQueryTextSubmit&中使用getFilter。 onQueryTextChange方法。我正在使用片段。

我的onQueryTextSubmit& onQueryTextChange方法工作正常。

这是我的onCreateOptionsMenu:

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

    SearchManager searchManager = (SearchManager)   this.getContext().getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView)   menu.findItem(R.id.action_search).getActionView();

      searchView.setSearchableInfo(searchManager.getSearchableInfo(getActivity().getComponentName()));
     searchView.setIconifiedByDefault(false);   

     SearchView.OnQueryTextListener textChangeListener = new  SearchView.OnQueryTextListener() 
    {
        @Override
        public boolean onQueryTextChange(String newText) 
        {
            // this is your adapter that will be filtered
         //   adapter.getFilter().filter(newText);
            //  adapter.getFilter().filter(newText);
            System.out.println("on text chnge text: "+newText);
            return true;
        }
        @Override
        public boolean onQueryTextSubmit(String query) 
        {
            // this is your adapter that will be filtered
         //  adapter.getFilter().filter(query);
        //  adapter.getFilter().filter(query);
            System.out.println("on query submit: "+query);
            return true;
        }
    };
    searchView.setOnQueryTextListener(textChangeListener);

  //   return super.onCreateOptionsMenu(menu);

}

以下是我的ListAdapter:

ListAdapter adapter = new SimpleAdapter(getActivity(), inboxList, R.layout.p_list_item,
                        new String[] { TAG_ID, TAG_FROM, TAG_COUNTRY, TAG_DATE, TAG_EMAIL, TAG_SUBJECT },
                        new int[] { R.id.from, R.id.subject, R.id.country, R.id.date, R.id.mail, R.id.roundscore }) {

1 个答案:

答案 0 :(得分:0)

将适配器设置为定义为

的全局变量
ListAdapter listAdapter;

在应用程序中实现searchView之前,请确保适配器显示相应的结果,如果是,则执行搜索

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

    MenuItem item = menu.findItem(R.id.search_menu);
    SearchView searchView = (SearchView) item.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            listAdapter.getFilter().filter(newText);
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}