Android dynamically displays data based on EditText search box listview

Source: Internet
Author: User

According to the EditText search box ListView Dynamic Display data is based on demand, think that the things involved may be more interesting, so write a write, I hope that a little help.


First, let's analyze the whole process:

1. Create a layout that contains a edittext search box and a ListView

2. Create a DataSet Mdata, for adapter creation of the ListView

3. Add edittext text Change listener

4. Dynamically update the ListView with Notifydatasetchanged ()


First step: Create a search box

This is still relatively easy, here I use is http://blog.csdn.net/walker02/article/details/7917392 the text box of the article, has the Point Fork full deletion function, however, deleted the search button, because we dynamic search, The button is not available.

Add a relativelayout layout, then add two controls to it (specifically 3),


The effect is as above, the XML code is as follows:

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:context = "Com.ricawinter.dynamicsearch.mainactivity$placeholderfragment" > <relativelayout android:id= "@+id/top" and Roid:layout_width= "Fill_parent" android:layout_alignparenttop= "true" android:paddingleft= "10DP" android:paddingRi ght= "10DP" android:background= "@drawable/top_background" android:layout_height= "wrap_content" > &lt ; Relativelayout android:id= "@+id/rlsearchframedelete" android:layout_width= "Fill_parent" a ndroid:layout_height= "Wrap_content" android:layout_centervertical= "true" android:gravity= "Center_ver Tical "> <edittext android:id=" @+id/etsearch "android:layout_width=" Fill_parent "Androi d:layout_height= "Wrap_content" Android:singlelIne= "true" android:background= "@drawable/search_frame" android:layout_marginright= "10DP" Android:padd ingleft= "32DP" android:textsize= "12SP" android:hint= "Searching ..."/> <imageview android:id= "@+i D/ivdeletetext "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:layo Ut_alignparentright= "true" android:src= "@drawable/delete" android:layout_centerinparent= "true" Androi d:paddingright= "20DP" android:visibility= "Gone"/> </RelativeLayout> <         /relativelayout> <listview android:id= "@+id/mlistview" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" android:layout_below= "@+id/to P "> </ListView></RelativeLayout>


Step Two: Create a DataSet Mdata

Simpleadapter is used here, so the dataset is created in the format of my own, according to their own adapter to build metadata, stored in Mlisttitle and mlisttext data is not to change, and Mdata will be in the text box changes, Mdata data will be changed accordingly, this is the update operation needs to do. Here is the creation of the metadata set,

The code is as follows:

        ListView Mlistview;        arraylist<map<string, object>> mdata = new arraylist<map<string, object>> ();        arraylist<string> mlisttitle = new arraylist<string> ();                arraylist<string> mlisttext = new arraylist<string> (); private void Getmdata (arraylist<map<string, object>> mdatas)     {    Map<s Tring, object> item = new hashmap<string, object> ();    Mlisttitle.add ("This is a title!");     Mlisttext.add ("This is a text.\n2014.09.18.16.33");       item.put ("Ti Tle ", Mlisttitle.get (0));    Item.put (" text ", Mlisttext.get (0));    Mdatas.add (item) ;    Mlisttitle.add ("This was an another title!");     Mlisttext.add ("This was an another text.\n2014.09.18.16.33");        IT EM = new Hashmap<strinG, object> ();    Item.put ("title", Mlisttitle.get (1));    Item.put ("text", MLISTT Ext.get (1));    Mdatas.add (item);   }

And then use Mdata to create adapter

    private void Set_mlistview_adapter ()    {    Mlistview = (ListView) Findviewbyid (R.id.mlistview);                Getmdata (mdata);                adapter = new Simpleadapter (this,mdata,android. R.layout.simple_list_item_2,     new string[]{"title", "Text"},new int[]{android. R.id.text1,android. R.ID.TEXT2});            Mlistview.setadapter (adapter);    }

By this, the state of the program's start is displayed. If you don't have a search box, you can do it here.


Step three: Add EditText's text-changing listener

Because we want to dynamically modify the display of the ListView, we have to listen and then do the corresponding action. When the supervisor hears the text change, it uses handler post a runnable to make the corresponding change.

private void Set_esearch_textchanged () {esearch = (EditText) Findviewbyid (R.id.etsearch); Esearch.addtextchangedlistener (New Textwatcher () {@Override public void ontextchanged (Charsequence arg0, int arg1, int arg2, int arg3) {//TODO auto-generated Method Stub//This should be the action to be done at the time of the change, it's useless.         。 } @Override public void beforetextchanged (Charsequence arg0, int. arg1, int arg2, in         T arg3) {//TODO auto-generated Method Stub//This is the action that will be performed before the text box changes} @Override public void aftertextchanged (Editable s) {//TODO auto-generated method stub/** This is the text box change                 The action that will be performed * because all we have to do is change the text box, and the data of our ListView changes accordingly, and is displayed as if it were on the interface.                 * So here we need to add the data to modify the action.               */if (s.length () = = 0) {ivdeletetext.setvisibility (View.gone);//When the text box is empty, the fork disappears              } else {ivdeletetext.setvisibility (view.visible);//When the text box is not empty, fork myhandler.post is present (EC               hanged);    }         }    }); }


Handler here embodies a huge use, we can according to the handler of such a post function, can be the interface God horse to do their own want to change, can not only be modified by the ListView, like every input word, the font changed into another color, can be.


Fourth step: Dynamically update the ListView with Notifydatasetchanged ()

Back to the point, here is the most important step, we post out, then we will be based on the text of the search text box and then filter the metadata, and then let the matching data display on the ListView.

(/* ya, top S4 in writing blog, is not a sin ... * *)

Adapter has a notifydatasetchanged () method that updates the bound ListView with this method when the data is updated, with the following effect:

Enter a 5 or there is two item, my choice is, as long as the title and text contain the character of the textbox, that is, the target item

When input 50 o'clock, because only one item in the title or text contains the text of the search box, so only the inclusion of this one

Plus a 0, because the text without item contains 500, so the ListView has no item


Successful completion of the effect, awesome, LZ level too dishes, encountered a few problems.

Here are some questions you might encounter:

1, notifydatasetchanged (), this update, the Mdata data set did change, but the ListView is not updated. I was like this before, and later found that the reference to the Mdata dataset changed, so adapter again notify is useless, because adapter is bound with the reference of the Mdata, reference a change, then the data will not be updated to the ListView. That's why I use the Get function parameter to pass a reference, and if you return a reference directly back, that's the problem, so you need to be careful. can refer to http://www.2cto.com/kf/201401/273017.html


2, on the interface UI update, you can use handler, through post a runnable to update, runnable will go to the text of the search box to update the data in Mdata.

The code is as follows:

Runnable echanged = new Runnable () {    @Override public    void Run () {          //TODO auto-generated method stub          Stri ng data = Esearch.gettext (). toString ();          Mdata.clear ();          Getmdatasub (mdata, data);          Adapter.notifydatasetchanged ();    }};


3, may have the understanding of mdata a bit of a problem, because after the data update, each time the screening data are placed in the Mdata, then the original data, of course, is in Mlisttitle and Mlisttext. It is known based on the Getmdatasub code that obtains the data.

private void Getmdatasub (arraylist<map<string, object>> mdatasubs, String data) {     int length = Mlisttitle.size ();     for (int i = 0; i < length; ++i) {           if (mlisttitle.get (i). Contains (data) | | mlisttext.get (i). Contains (data) {                map<string,object> item = new hashmap<string,object> ();                Item.put ("title", Mlisttitle.get (i));                Item.put ("text",  mlisttext.get (i));                Mdatasubs.add (item);}}}         


4, because the text box in the first, so the program is running, the text box will get the focus, and then pop-up input method, here use in the XML file to add a long width of 0 linearlayout to get the focus, the code is as follows:

<!--to  acquire Focus--><linearlayout      android:focusable= "true"      Android:focusableintouchmode = "true"      android:layout_width= "0px"      android:layout_height= "0px"/>


In summary, this dynamic approach may also need to be improved, such as the filtering method, and the control is only for Sampleadapter's ListView, if it is a custom ListView, it should be able to be optimized. There is the setting of the height of the ListView, set into Wrap_content and fill_parent two methods actually replaced by real machine can experience two kinds of gap, more obvious bar, is the process of downward stroke.

The writing is relatively simple and rough, do not take too much offense. Attach a copy of the code

Always like to share, so download for free. Poke a punch


Android dynamically displays data based on EditText search box listview

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.