Android implements the countdown function for item in a ListView or GridView

Source: Internet
Author: User

sometimes in development you may encounter a time when you need to make ListVieworGridViewin the correspondingItemthe need to do the countdown, at this point, if you still follow a commonListVieworGridViewof theAdapterthe wording+timing function to implement the words, then when scrollingListVieworGridViewthe time,ItemThere may be a reuse problem (i.e. no reciprocal or currentItemThe countdown is over, but there is a reciprocal phenomenon), so in order to solve this problem, we need to iterate over the collection of the current object and then reduce the corresponding time value for each object1, and then finally throughAdapterof thenotifydatasetchangedmethod static Refresh interface. the effect is as follows:

the code for Mainactivity is as follows:

Package Com.abner.countdownforlistview;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.support.v7.app.appcompatactivity;import Android.widget.listview;import Java.util.arraylist;import Java.util.list;public class Mainactivity extends Appcompatactivity {private ListView Lv_goo    ds    Private Goodsadapter adapter;    private int result =-1; Private Handler Handler = new Handler () {@Override public void Handlemessage (Message msg) {Supe            R.handlemessage (msg);                if (msg.what = = 1) {result = Adapter.countdowntime ();                    if (result = = 0) {handler.removemessages (1);                Return                    } else {adapter.notifydatasetchanged ();                Handler.sendemptymessagedelayed (1, 1000);    }            }        }    }; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (saveDinstancestate);        Setcontentview (R.layout.activity_main);        Lv_goods = (ListView) Findviewbyid (r.id.lv_goods);    InitData ();        } private void InitData () {list<goods> goodslist = new arraylist<> ();            for (int i = 0; i < i++) {Goods Goods = new Goods ();            Goods.setgoodsname ("This is the product name:" + i);            Goods.setprice (i * 26);            Goods.settime (i% 3 = = 0? I * 8 + 62:0);        Goodslist.add (goods);        } adapter = new Goodsadapter (this, goodslist);        Lv_goods.setadapter (adapter);    Handler.sendemptymessagedelayed (1, 1000); }}

In thismainactivity, you can see theHandlerThe reciprocal function is achieved,ListViewSetup is completeAdapterafter that throughHandlerof thesendemptymessagedelayedMethod sends a message, and then theHandlerof theHandlemessagemethod by calling the declared in the adapterCountdowntimemethod iterates over the corresponding set of objects, sets the corresponding values, and finally returns theresultTo determine if the countdown has ended, remove the message if it has ended, or continue to send the message to the countdown operation。

The code for the ListView goodsadapter is as follows:

Package Com.abner.countdownforlistview;import Android.content.context;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.textview;import java.util.list;import Static com.abner.countdownforlistview.r.id.tv_price;/** * Created by Abner on 2016/5/6.    */public class Goodsadapter extends Baseadapter {private context context;    Private list<goods> goodslist;        Public Goodsadapter (context context, list<goods> goodslist) {this.context = context;    This.goodslist = goodslist;    } @Override public int getcount () {return goodslist = = null? 0:goodslist.size ();    } @Override public Object getItem (int position) {return goodslist.get (position);    } @Override public long getitemid (int position) {return position;     } @Override public View getView (int position, view Convertview, ViewGroup parent) {   Final Viewholder Holder;            if (Convertview = = null) {holder = new Viewholder ();            Convertview = Layoutinflater.from (context). Inflate (R.layout.lv_goods_item, NULL);            Holder.tv_goodsname = (TextView) Convertview.findviewbyid (r.id.tv_goodsname);            Holder.tv_price = (TextView) Convertview.findviewbyid (Tv_price);            Holder.tv_time = (TextView) Convertview.findviewbyid (r.id.tv_time);        Convertview.settag (holder);        } else {holder = (Viewholder) convertview.gettag ();        } final Goods Goods = goodslist.get (position);        Holder.tv_goodsName.setText (Goods.getgoodsname ());        Holder.tv_price.setText ("¥" + Goods.getprice ());        Final int time = Goods.gettime ();        if (Time > 0) {holder.tv_time.setText (Gettimestr (time) + "after start");        } else {Holder.tv_time.setText ("in progress ...");    } return Convertview; } class Viewholder {TextView tv_goodsName;        TextView Tv_price;    TextView Tv_time;    } private int result =-1;             /** * Countdown, update the display time of each item in real time * * @return */public int countdowntime () {New Thread (new Runnable () {                    @Override public void Run () {try {thread.sleep (1000);                        if (goodslist = = NULL | | result = = Goodslist.size () + 1) {result = 0;                    Return                    } result = 1; for (Goods goods:goodslist) {if (goods.gettime () = = 0) {Goods.settim                            E (0);                        result++;                        } else {Goods.settime (Goods.gettime ()-1);                }}} catch (Interruptedexception e) {e.printstacktrace ();        }}). Start (); Log.i("Test", "result==>" + result);    return result; }/** * Formatted time display in the format: xx minutes xx seconds * * @param timediff * @return * */public static String gettimestr (int        Timediff) {int min = TIMEDIFF/60;        int sec = Timediff-min * 60;        String result = "";        if (min = = 0) {result = sec + "Second";        } else {result = min + "min" + sec + "second";    } return result; }}

In this case, the item in the ListView or GridView is implemented in Android The countdown function has been completed.

Source Download

Android implements the countdown function for item in a ListView or GridView

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.