3

在我的应用程序中,我正在使用可扩展列表视图。现在我想使用搜索框来显示过滤后的可扩展列表视图项目。为此,我使用以下代码

    search = (SearchView) findViewById(R.id.search);
    search.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
    search.setIconifiedByDefault(false);
    search.setOnQueryTextListener(this);
    search.setOnCloseListener(this);

但是这种编码只支持 API 11 以上。但我想在 API 11 以下实现这些功能。

这是使用编辑文本作为默认列表视图适配器的搜索视图的方式

  inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            MainActivity.this.adapter.getFilter().filter(cs);   
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub                          
        }
    });
4

2 回答 2

1

我所做的是,为什么要自己搜索我的数据。

我在 Actionbar 中添加了一个 TextView,并在我的 ListAdapter 中处理输入。

由于您的目标是 11 以下的 api,您要么必须添加 ActionBarSherlock,要么将 TextView 放在其他地方。

    EditText tv = new EditText(this);
    tv.setOnEditorActionListener(new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event.getAction() == KeyEvent.KEYCODE_ENTER) {
                yourAdapter.filterData(v.getText());
                return true;
            }
            return false;
        }
    });

这就是我将如何设计一个 textView 来处理搜索。您必须自己实现搜索,因为我的数据由 sqlite 数据库支持,所以我只需将搜索交给 sql 数据库。

public void filterData(String query){

  query = query.toLowerCase();
  Log.v("MyListAdapter", String.valueOf(continentList.size()));
  continentList.clear();

  if(query.isEmpty()){
   continentList.addAll(originalList);
  }
  else {

   for(Continent continent: originalList){

    ArrayList<Country> countryList = continent.getCountryList();
    ArrayList<Country> newList = new ArrayList<Country>();
    for(Country country: countryList){
     if(country.getCode().toLowerCase().contains(query) ||
       country.getName().toLowerCase().contains(query)){
      newList.add(country);
     }
    }
    if(newList.size() > 0){
     Continent nContinent = new Continent(continent.getName(),newList);
     continentList.add(nContinent);
    }
   }
  }

  Log.v("MyListAdapter", String.valueOf(continentList.size()));
  notifyDataSetChanged();

 }

您必须更新搜索方法以适合您的数据。

于 2013-10-14T08:44:53.927 回答
0

我认为您需要使用 actionBarCompat 来实现向后兼容性。 http://android-developers.blogspot.com/2013/08/actionbarcompat-and-io-2013-app-source.html

于 2013-10-14T08:51:56.657 回答