Android-simpleadapter Adapter supported components and ListView simulation Download

Source: Internet
Author: User

Originally this week wanted to write three articles, the result of this first article does not know how to pen. Language expression ability really need to improve AH. In fact, there are a lot of things to write, the recent days have come into contact with the previous heard but did not consider some of the points. The cause of this once did a problem, I did not understand, I see a comment or a lot of the same as I thought, have not had time to pursue, finally still worried, to see a bit, found that I was wrong. The original question is as follows:

Which of the following components is supported in the row layout using Simpleadapter as the adapter for the ListView?

    • TextView
    • ProgressBar
    • Compoundbutton
    • ImageView
I did not hesitate to choose ABCD, and then a red-red X. The answer is ACD. Simpleadapter not support ProgressBar, I was very puzzled, why?

Actually look at this question, people say is simpleadapter, take for granted Simpleadapter as the most basic adapter (as for other adapters, you can look at), so I feel the answer should be no problem, So what does this simpleadapter support? This will be from the source of Simpleadapter, I took the important to see, first look at the Simpleadapter constructor.

Public Simpleadapter (context context, list<?. extends Map<string,?>> data,int Resource, string[] from, int[] t O) {        mdata = data;        Mresource = Mdropdownresource = resource;        Mfrom = from;        MTo = to;        Minflater = (layoutinflater) context.getsystemservice (context.layout_inflater_service);}
This simpleadapter only a constructor, from the parameters can be seen, simpleadapter data resource type is still relatively fixed, list< Extends Map<string,?>>. Resource is the layout file for each record, from the key of the map in data, and to is the ID of the component in the layout file.

We know that adapter's view display or view binding is implemented in the GetView function, so Simpleadapter's GetView function, but Simpleadapter does not directly rewrite GetView, but instead calls other functions, Finally call a function called BindView, from the literal understanding is "bound view", so to see this function.

private void BindView (int position, view view) {final Map DataSet = mdata.get (position);        if (DataSet = = null) {return;        } final Viewbinder binder = Mviewbinder;        Final string[] from = Mfrom;        Final int[] to = mTo;        Final int count = To.length;            for (int i = 0; i < count; i++) {final View v = View.findviewbyid (to[i]);                if (v! = null) {final Object data = Dataset.get (From[i]); String Text = data = = null?                "": data.tostring ();                if (text = = null) {text = "";                } Boolean bound = false;                if (binder! = null) {bound = Binder.setviewvalue (V, data, text);  } if (!bound) {if (v instanceof checkable) {if (data instanceof            Boolean) {((checkable) v). setchecked ((Boolean) data);            } else if (v instanceof TextView) {//Note:keep the instanceof TextView check at                            The bottom of these//IFS since a lot of views is textviews (e.g. checkboxes).                        Setviewtext ((TextView) v, text);                                    } else {throw new IllegalStateException (V.getclass (). GetName () + "Should is bound to a Boolean, not a" + (data = = null? ")                        <unknown type> ": Data.getclass ())); }} else if (v instanceof TextView) {//Note:keep the instanceof TextView chec                        K at the bottom of these//IFS since a lot of views is textviews (e.g. checkboxes).                    Setviewtext ((TextView) v, text);   } else if (v instanceof ImageView) {if (data instanceof Integer) {                         Setviewimage ((ImageView) v, (Integer) data);                        } else {setviewimage ((ImageView) v, text);  }} else {throw new IllegalStateException (V.getclass (). GetName () + "is not a"                    + "view that can is bounds by this simpleadapter"); }                }            }        }    }

There's a long list of judgments in the bindview that we want to see,

if (v instanceof checkable) {     //...                 } else if (v instanceof TextView) {     //...                  } else if (v instanceof Imagev Iew) {     //...     } else {      throw new IllegalStateException (V.getclass (). GetName () + "is not a" + "                                view that C An is bounds by this simpleadapter ");}
Can see the first to determine whether this view is the implementation of the Checkable (interface), and then judge is not TextView, and then judge is not ImageView, and then there is no then, if the above three kinds are not, then throw the exception, is a illegal abnormal, illegal! The exception is that the view that will be bound is not a view that can be simpleadapter bound. So go to the past to see the problem, A, TextView, can; B, ProgressBar, what ghost? No. C, Compoundbutton, this view implements the Checkable interface, can be. D, ImageView, no problem.

So the answer is obvious.

In fact, Simpleadapter is easy to use and can also achieve a relatively good layout, if using Simpleadapter, I wrote a very simple way to get the data source, as follows:

Private list<map<string, object>> GetData () {<span style= "white-space:pre" ></span>mdata = new Arraylist<map<string, object>> (); for (int i = 1; i <; i++) {map<string, object> Map = new hashmap& Lt String, object> (); Map.put ("name", "name" + i + "\ n" + "Here is the description of the item"), Map.put ("button", "Download"); Map.put ("Image", R . Drawable.ic_launcher); Mdata.add (map);} return mdata;}
Then just new one simpleadapter on the line:

Simpleadapter madapter = new Simpleadapter (Getapplicationcontext (), GetData (), R.layout.item, new string[] {"Image", " Name "," button "}, new int[] {r.id.id_item_image,r.id.id_item_text, r.id.id_item_btn});

As for the layout file, it's easier.

This is not much to say, but the feeling has been said a lot, there is a lot of nonsense. Because of this reason, I would like to imitate some download software app in the list download style, in fact, put progress in the ListView, since Simpleadapter does not support ProgressBar, then rewrite Baseadapter. This is a very simple rewrite, in the simulation download did not use the service, that is, there is no simulation background download, just in the current activity inside the simulation download.

I rewrote the adapter as follows:

public class Myadapter extends Baseadapter {private list<map<string, object>> mdata;private Context mcontext ;p rivate layoutinflater minflater;public myadapter (Context context,list<map<string, object>> data) { This.mcontext = Context;this.mdata = Data;this.minflater = Layoutinflater.from (context);} @Overridepublic int GetCount () {//TODO auto-generated method Stubreturn mdata.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn mdata.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {MyView MView = null; Buttonlistener Mlistener = null;if (Convertview = = null) {MView = new MyView (); Convertview = Minflater.inflate ( R.layout.item, null); Mview.imageview = (ImageView) Convertview.findviewbyid (r.id.id_item_image); Mview.textview = ( TextView) Convertview.findviewbyid (r.id.id_item_text); Mview.buttOn = (Button) Convertview.findviewbyid (r.id.id_item_btn), Mview.progressbar = (ProgressBar) Convertview.findviewbyid ( r.id.id_item_progress); mlistener = new Buttonlistener (position, Mview.progressbar); Convertview.settag (MView);} Else{convertview = (View) Convertview.gettag ();} map<string, object> map = mdata.get (position); MView.imageView.setImageResource ((Integer) map.get ("image")); MView.textView.setText ((charsequence) map.get ("name"), MView.button.setText ((charsequence) map.get ("button")); MView.progressBar.setProgress (0); MView.button.setOnClickListener (Mlistener); return convertview;} Class Myview{imageview ImageView; TextView TextView; Button button; ProgressBar ProgressBar;} Class Buttonlistener implements Onclicklistener{button button;private int mposition;private ProgressBar Mprogressbar; private int mprogress = 0; Thread Mthread = null;private Boolean flag = true; Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {button.settext ("OK");};}; Class DownloadtHread extends thread{@Overridepublic void Run () {while (Mprogress<=100&&flag) {mprogressbar.setprogress ( mprogress); try {thread.sleep (+); mprogress + = 2;} catch (Interruptedexception e) {e.printstacktrace ();}} if (mprogressbar.getprogress () ==100) {flag = false;handler.sendemptymessage (0);}}} Public Buttonlistener (int position,progressbar ProgressBar) {mposition = Position;mprogressbar = ProgressBar;} @Overridepublic void OnClick (View v) {button = (button) v;if (Button.gettext (). Equals ("Download")) {Button.settext (" Pause "), if (mthread==null) {mthread = new Downloadthread ();} Mthread.start ();} else if (Button.gettext (). Equals ("Pause") &&mprogressbar.getprogress () <100) {mthread.interrupt (); Mthread = Null;flag = False;button.settext ("Go On");} else if (Button.gettext (). Equals ("Go On") &&mprogressbar.getprogress () <100) {flag = true;if (Mthread = = null) {mthread = new Downloadthread ();} Mthread.start (); Button.settext ("Pause");} Else{flag = False;mthread.interrupt (); mthread = Null;bUtton.settext ("OK");}}} 

It's not difficult here, just a few points to note:

1, to each item in the button binding listener event, in the listener constructor, I passed in the current item position, and the item in the ProgressBar, this position here seems to be useless.

2, open the new thread in the onclick, simulate the download. In fact, it should be open a service, in the service to open a new thread simulation download, so that is back off the current activity, download is still in progress, here is just a simple foreground simulation.

3. When the text on the button changes when the download is complete, you need to return to the UI thread, which is mainthread, otherwise it will crash.

4, when the Mthread stop, please do not use stop this method, this method does not have any eggs, after use no matter how stop, you will see your ProgressBar still running, in fact, the Stop method is executed after the run function. Even if you do not run out of the call, he still needs to run out the run function. The interrupt () method is used here to empty its own thread after use. When turned on, re-new one. And in the condition of while judge added a more flag variable, auxiliary control download.

Run by:


Well, the interface is a bit ugly, as for the UI or something, let the artist do it.

As for how to replicate the adapter I will not say, this is not the issue of concern.

My Code does not write well, if there is a better way, please tell me, kneeling thanks.

As for the optimization of the ListView, I will write an article later.


Another two articles this week, an article about fragment, a custom view.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android-simpleadapter Adapter supported components and ListView simulation Download

Related Article

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.