2017-04-23 92 views
-1

如何在我的android應用程序中添加搜索功能?我有一個listview,我想添加搜索功能。我有代碼,但我不知道如何將其與我的應用程序正確集成。下面是代碼:如何添加搜索?

private ListView listView; 
List<Dog> dogs = new ArrayList<>(); 
int dataSize; 
String[]breed; 
public Dog listDog = new Dog(); 
private SearchView searchView; 
ArrayAdapter<String>adapter = null; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    searchView = (SearchView)findViewById(R.id.search); 
    initInstances(); 
    setupSearchView(); 
} 

private void initInstances() { 

    prepareData(); 

    ListAdapter adapter = new ListAdapter(MainActivity.this, listDog); 
    listView = (ListView) findViewById(R.id.list_item); 
    listView.setAdapter(adapter); 
    listView.setOnItemClickListener(listViewClickListener); 
} 

private void setupSearchView() { 
    searchView.setIconifiedByDefault(false); 
    searchView.setOnQueryTextListener(this); 
    searchView.setSubmitButtonEnabled(true); 
    searchView.setQueryHint("Искать кота"); 
} 

private void prepareData() { 

    int resId[] = {R.drawable.german_shepherd, R.drawable.labrador_retriever, R.drawable.blue_dog, R.drawable.beagle 
      , R.drawable.boxer, R.drawable.golden_retriever, R.drawable.poodle, R.drawable.pug, R.drawable.siberian_husky, 
      R.drawable.great_dane, R.drawable.german_shepherd, R.drawable.labrador_retriever, R.drawable.blue_dog, R.drawable.beagle 
      , R.drawable.boxer, R.drawable.golden_retriever, R.drawable.poodle, R.drawable.pug, R.drawable.siberian_husky, 
      R.drawable.great_dane, R.drawable.german_shepherd, R.drawable.labrador_retriever, R.drawable.blue_dog, R.drawable.beagle 
      , R.drawable.boxer, R.drawable.golden_retriever, R.drawable.poodle, R.drawable.pug, R.drawable.siberian_husky, 
      R.drawable.great_dane, R.drawable.german_shepherd, R.drawable.labrador_retriever, R.drawable.blue_dog, R.drawable.beagle 
      , R.drawable.boxer, R.drawable.golden_retriever, R.drawable.poodle, R.drawable.pug, R.drawable.siberian_husky, 
      R.drawable.great_dane}; 

    breed = new String [] {"German shepherd", "Labrador retriever", "Bull dog", "Beagle", 
      "Boxer", "Golden retriever", "Poodle", "Pug", "Siberian husky", 
      "Great dane", "German shepherd", "Labrador retriever", "Bull dog", "Beagle", 
      "Boxer", "Golden retriever", "Poodle", "Pug", "Siberian husky", 
      "Great dane", "German shepherd", "Labrador retriever", "Bull dog", "Beagle", 
      "Boxer", "Golden retriever", "Poodle", "Pug", "Siberian husky", 
      "Great dane", "German shepherd", "Labrador retriever", "Bull dog", "Beagle", 
      "Boxer", "Golden retriever", "Poodle", "Pug", "Siberian husky", 
      "Great dane"}; 


    String description[] = {getString(R.string.Юлмарт), getString(R.string.ЮлияСадовая), getString(R.string.Ювелирныймагазин585), getString(R.string.Альфа) 
      , getString(R.string.Электромонтаж), getString(R.string.АгрокомплексКарла93), getString(R.string.АгрокомплексКарла363), getString(R.string.ДобрыеСемена), getString(R.string.АгрокомплексКрасная93) 
      , getString(R.string.Глобус), getString(R.string.ПланетаДетства), getString(R.string.АгрокомплексКрасная152), getString(R.string.Золушка), getString(R.string.Офискласс118) 
      , getString(R.string.СалонцветовLadyFlower), getString(R.string.ДекорЮг), getString(R.string.Глобус), getString(R.string.АгрокомплексКрасная25), getString(R.string.ОфисКласс106) 
      , getString(R.string.ПятёрочкаБувальцева26), getString(R.string.БаронДиваноффКрасная1), getString(R.string.Рынок), getString(R.string.Новинтех), getString(R.string.ГлорияДжинс) 
      , getString(R.string.ЦифровойсупермаркетDNS), getString(R.string.Евроремонт), getString(R.string.Гейзер), getString(R.string.Нива), getString(R.string.ДвериАдамКомунистическая20) 
      , getString(R.string.ЦветыДоставка), getString(R.string.БытКубани), getString(R.string.РынокКореновскоеРАЙПО), getString(R.string.Золушка), getString(R.string.ДинскиеКолбасы) 
      , getString(R.string.Цветы), getString(R.string.Тимур), getString(R.string.АгрокомплексКомунистическая20), getString(R.string.АгрокомплексКарла363), getString(R.string.МебельныймагазинРз59) 
      , getString(R.string.Изумруд),}; 
    dataSize = resId.length; 
    adapter = new ArrayAdapter<String>(this, R.layout.list_item,breed); 

    Log.d("khem", "dataSize " + resId.length); 
    Log.d("khem", "breed " + resId.length); 
    Log.d("khem", "description " + resId.length); 



    for (int i = 0; i < dataSize; i++) { 
     Log.d("khem", " " + i); 
     Dog dog = new Dog(resId[i], breed[i], description[i]); 
     dogs.add(dog); 
    } 

    listDog.setDogs(dogs); 

    //Log.d("khem",listDog); 
} 

public boolean onQueryTextSubmit(String query) { 
    return false; 
} 


public boolean onQueryTextChange(String newText) { 
    if (TextUtils.isEmpty(newText)) { 
     listView.clearTextFilter(); 
    } else { 
     listView.setFilterText(newText.toString()); 
    } 
    return true; 
} 

/************************* 
* Listener 
***************************/ 

AdapterView.OnItemClickListener listViewClickListener = new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     Toast.makeText(MainActivity.this, "POSITION:= " + position, 
       Toast.LENGTH_SHORT).show(); 

     Intent intent = new Intent(MainActivity.this,ShowDetailActivity.class); 
     intent.putExtra("resId",listDog.getDogs().get(position).getResId()); 
     intent.putExtra("breed",listDog.getDogs().get(position).getBreed()); 
     intent.putExtra("desc",listDog.getDogs().get(position).getDescription()); 

     startActivity(intent); 
    } 

}; 
} 

回答

0

1更改ListAdapter到SimpleAdapter

2 - 使適配器的全局變量,

那麼你可以用用getFilter方法

注:我m從editText獲取要搜索的單詞中的單詞,並在使用TextChanged監聽器寫入單詞時執行搜索

EditText grabResults; 
grabResults.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 


       adapter.getFilter().filter(s); 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    }); 

你可以把任何你想:)

adapter.getFilter().filter(s); 
相關問題