Android add custom search bar in application

巧了我就是萌 提交于 2019-12-06 12:35:57

问题


I want to implement search bar in my application which will filter list view depending on letters entered in edit text. Here is what I have actually like a design

So I want to filter the elements by title so I guess I have to change the sqlite statement, because I'm populating the listview from database.

And I have two question :

1.Which is the best way to implement custom search bar : add textwatcher to an edit text and change the sqlite statement everytime user enter letter or ?

2.How to sort in sqlite depending on letters entered from user. If user press A I want to show all items which have that letter no matter if it's in the beginning or in the end.


回答1:


So the things to achieve this are very simple, no matter what kind of Adapter are you using. First you need to create TextWatcher and add it to your Edit Text. Than in your onAfterTextChanged() you can create your new SQL statement like :

String sql = "SELECT title FROM cards WHERE title LIKE '%"+someString+"%'"
//where someString is `Charsequence` which you get in your onAfterTextChanged()

Before getting your data again if you are using ArrayList or any other kind of Lists for storing your data you have to clear them, so you can get the new data. And than you can simply call adapter.notifySetDataChanged(). And it should work. At least this is the way how I'm doing this. Maybe it's not the best way, but it's working.




回答2:


What is the size of your database? if it is not a BIG one then i think the simple SQL should work for you:

SELECT  Column1, Column2
FROM    myTable
WHERE   myColumn LIKE 'somecharacter%'

You can call to DB while the user is typing or can use some other logic like when the user press a specific button.



来源:https://stackoverflow.com/questions/8848100/android-add-custom-search-bar-in-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!