简体   繁体   中英

Android Search Activity

I have created an application which is just a list view with some values in it and each time I click an item, it starts a new intent. I want my list to be searchable, so I have added a search button on top of it.

I have seen some examples that uses local databases but I did not find a complete tutorial on how to implement this in my application.

What is the best way to do this? Can anyone reference me to a good site with examples or explain to me how this works?

This is not as straightforward as it might seem, but simple enough. You want to make your adapter (you need to have a custom adapter) implement the Filterable interface. Then when you "perform the filtering" you perform the query in the database and return the updated results, calling notifyDatasetChanged() . I couldn't find a good example quickly, but this one is good enough.

After that, you need to "connect" both the adapter's filter and an EditText. Add a TextWatcher to the EditText and in the afterTextChanged() call getFilter().filter(theText) .

That's more or less it.

See this demo.

I have implemented the ListView with search features based on the text entered in to EditText.

@Override
public void afterTextChanged(Editable s) {}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    searchTextLength = searchEditText.getText().length();
    m_orders.clear();
    m_orders = new ArrayList<SearchData>();
    //SearchData o1 = new SearchData();
    SearchData o[]=new SearchData[search_list.length];
    for(int i=0; i<search_list.length; i++)
    {
        if(searchTextLength <= search_list[i].length())
        {
            if(searchEditText.getText().toString().equalsIgnoreCase((String) search_list[i].subSequence(0, searchTextLength)))
            {
                o[i]=new SearchData();
                o[i].setTitleName(search_list[i]);
                o[i].setsubTitleName(subTitle_list[i]);
                m_orders.add(o[i]);
            }
        }
    }

    this.m_adapter = new OrderAdapter(this, R.layout.search_row, m_orders);
    lv.setAdapter(this.m_adapter);
    m_adapter.notifyDataSetChanged();
    //getOrders();

    //lv1.setAdapter(new ArrayAdapter<String>(SearchActivity.this,R.layout.search_layout , arr_sort));
}

Hope it will help you for your condition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM