在Listview中过滤搜索视图的结果

时间:2016-03-25 10:23:18

标签: android database listview searchview

我的操作栏中有一个SerchView功能。它工作正常。它从我创建的数据库中获取信息。但是,我尝试使用ListView而不是PopupDropDown来过滤结果。有些不对劲。这是我的代码。

public class SearchViewNaListview extends Activity implements OnQueryTextListener {



public static final String PREFS_NAME = "MyPrefsFile1";
private ListView mListView;

ArrayList<WordDefinition> allWordDefinitions=new ArrayList<WordDefinition>();


DictionaryDatabase DictionaryDatabase;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);



    mListView = (ListView) findViewById(R.id.list);
    mListView.setAdapter(new ArrayAdapter <WordDefinition>(getApplicationContext(),android.R.layout.simple_list_item_1,allWordDefinitions));
    mListView.setTextFilterEnabled(true);



    DictionaryDatabase=new DictionaryDatabase(this); 
    allWordDefinitions=DictionaryDatabase.getAllWords(); 




    Collections.sort(allWordDefinitions, new CustomComparator());   


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
 // Inflate the menu; this adds items to the action bar if it is present.
 getMenuInflater().inflate(R.menu.main, menu);
 SearchManager searchManager = (SearchManager) getSystemService( Context.SEARCH_SERVICE );
       SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

       searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
       searchView.setSubmitButtonEnabled(true);
       searchView.setOnQueryTextListener(this);

       return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onQueryTextChange(String newText)
{
 // this is your adapter that will be filtered
     if (TextUtils.isEmpty(newText))
     {
           mListView.clearTextFilter();
       }
     else
     {
           mListView.setFilterText(newText.toString());
       }

     return true;
}

@Override
public boolean onQueryTextSubmit(String query) {
 // TODO Auto-generated method stub
 return false;
}


public class CustomComparator implements Comparator<WordDefinition> { // Para Listar em Ordem Alfabética ListView
       @Override
       public int compare(WordDefinition p1, WordDefinition p2) {
          return p1.word.compareToIgnoreCase(p2.word);
       }
    }
 }

1 个答案:

答案 0 :(得分:1)

您的Adapter是否实施了Filterable - 界面?请参阅setTextFilterEnabled