Android App--use Getitemviewtype to set different layouts for the ListView item

Source: Internet
Author: User

I. Overview

In the project's requirements, there is a need to display a list of transactions, this list is easy to associate with the ListView to implement, but this list is slightly different, it is the item is not the same layout, some of which shows the record of consumption, In some places, the record of top-up is displayed, which corresponds to the different item layout. Moreover, these two places are to obtain the data from the service side, these two item's data corresponding class content also is different, how should handle?

Step by step to achieve this effect.

Second, look first


Third, the realization step

The implementation of the principle is the adapter of the ListView is a key method is Getitemviewtype (Getitemviewtype), this method has a parameter is position, With this position, we can handle different data in different locations in the list collection, identify different types, and classify the data in the list.

First, the preparation of the data:

{"Status_code": "0", "result": [{"mr_content": {"point": "10", " Member_money ":" "," "Pay_money": "200", "Cash": "$", "bonus": "Consumption of 5 yuan at the end of the cost of more than a few million"            0 Yuan Meal Voucher 1 "," Activities ":" Three pot chicken 1 yuan ren eat "," coupon ":" Full 100 send "," Branch_name ":" Cosmopolitan " }, "mr_id": "" "," Mr_createtime ":" 1333333333 "," Mr_type ":" 0 "," u        ser_id ":" 108 "," merchant_id ":" 1 "," branch_id ":" 1 "," Branch_name ":" FFFF "},            {"Mr_content": {"Member_money": "$", "Branch_name": "Cosmopolitan"}, "mr_id": "A", "Mr_createtime": "1333333333", "Mr_type": "1", "user_id": "108" , "merchant_id": "1", "branch_id": "1", "Branch_name": "FFF"}], "Status_de SC ":" OK "}

You can see that mr_content this field, is a custom object, but the content of the two mr_content is different, here is the content of mr_content respectively to define two different classes or how to handle it?

In the beginning, I defined different classes for the two mr_content, and later found that this would not work, because when you define the outer class, mr_content cannot specify the data type. So, at the end of someone's way to define mr_content as a class, two different mr_content fields are defined, no problem occurs when parsing, no data will show null

Here is the data type of the Mr_content field I defined Comsumandchargerecordbean

public class Comsumandchargerecordbean {private string Branch_name;private string Pay_money;private string coupon;// Use the privileged private string Activities;private string Member_money;private string Cash;private string point;private string bonus ;//private string prestore_money;//Pre-deposit public string Getbranch_name () {return branch_name;} public void Setbranch_name (String branch_name) {this.branch_name = Branch_name;} Public String Getpay_money () {return pay_money;} public void Setpay_money (String pay_money) {This.pay_money = Pay_money;} Public String Getcoupon () {return coupon;} public void Setcoupon (String coupon) {this.coupon = coupon;} Public String getactivities () {return activities;} public void Setactivities (String activities) {this.activities = activities;} Public String Getmember_money () {return member_money;} public void Setmember_money (String member_money) {This.member_money = Member_money;} Public String GetCash () {return cash;} public void Setcash (String cash) {This.cash = cash;} Public String GetpoInt () {return point;} public void SetPoint (String point) {this.point = point;} Public String Getbonus () {return bonus;} public void Setbonus (String bonus) {this.bonus = bonus;}}


The data is ready, and the following is the display in the incoming ListView:

Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <include        android:id= "@+id/traderecord_layout"        layout= "@layout/topview _activity "/>    <listview        android:id=" @+id/lv_my_traderecord "android:layout_width=" Match_        Parent "        android:layout_height=" match_parent ">    </ListView></LinearLayout>

Two different item layout files are omitted, I believe everyone will, this is no difficulty

Here is the main interface code:

<pre class= "java" name= "code" >protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.activity_trade_record); MListView = (ListView) Findviewbyid (R.id.lv_my_traderecord); E_temptraderecordadapter adapter = new E_temptraderecordadapter (E_traderecordactivity.this, mymodel.traderecordlist ); Mlistview.setadapter (adapter); adapter.notifydatasetchanged ();}

The following is part of the code for the adapter adapter:

Fields and constructors:

private static final String TAG = "E_traderecordadapter";p rivate static final int type_count = total number of 2;//item types private static Final int type_comsum = 0;//consumption type private static final int type_charge = 1;//Recharge type Private arraylist<traderecordbean> D Atalist = new arraylist<traderecordbean> ();//Data set private Context mcontext;private int currenttype;// Current item Type Public e_temptraderecordadapter (Context mcontext,arraylist<traderecordbean> dataList) {super (); This.datalist = Datalist;this.mcontext = Mcontext;}

Several important methods:

@Overridepublic int GetCount () {//TODO auto-generated method Stubreturn datalist.size ();} @Overridepublic Object getItem (int position) {//TODO auto-generated method Stubreturn datalist.get (position);} @Overridepublic long Getitemid (int position) {//TODO auto-generated method Stubreturn position;}

Gets the number of the type of the child item get type This is determined by the field Mr_type, which is based on this field to determine the type of consumption record. In short, there must be a tag to differentiate the item when you set a different layout for item, and you can use this as a token of your judgment to set a different type.

@Overridepublic int Getitemviewtype (int position) {//TODO auto-generated method Stubif ("0". Equals (Datalist.get ( Position. Getmr_type ())) {return type_comsum;//consumption type} else if ("1". Equals (Datalist.get (position). Getmr_type ())) { return type_charge;//Recharge Type} else {return 100;}} @Overridepublic int Getviewtypecount () {return type_count;}

Viewholder: Caching These TextView controls

/** * Consumption record * @author YL * */class comsumviewholder {TextView branchnamecom; TextView Comsumemoney; TextView Useprevillage; TextView Yuezhifu; TextView cash; TextView Thisscore; TextView Extrareward; TextView Prestoremoney;} /** * Recharge Record * @author YL * */class chargeviewholder {TextView branchnamecha; TextView Prestoremoney; TextView Extrasmoney; TextView Totalmoney;}


And finally the GetView method: One of the key methods

Currenttype = Getitemviewtype (position);

This method gets the type of the current position, that is, the type set in the previous Getitemviewtype method.

The use of Convertview for reuse and holder is an optimization of the ListView.

When currenttype = = Type_comsum, the consumption type is loaded Comsumview = Layoutinflater.from (Mcontext). Inflate (r.layout.traderecord_item_ Comsume, null); The layout file for the consumption type. Instead, load the layout file of the recharge type. This allows you to set up a different layout file for different item.

Public View GetView (int position, View Convertview, ViewGroup parent) {//TODO auto-generated method Stubview Comsumview = Null View Chargeview = null; Comsumandchargerecordbean record = (Comsumandchargerecordbean) datalist.get (position). Getmr_content (); currentType = Getitemviewtype (position); if (Currenttype = = type_comsum) {Comsumviewholder Comsumholder = null;if (Convertview = = null) {Comsumholder = new Comsumviewholder (); Comsumview = Layoutinflater.from (Mcontext). Inflate (R.layout.traderecord_item _comsume, null); comsumholder.branchnamecom = (TextView) Comsumview.findviewbyid (r.id.tv_branch_name); Comsumholder.comsumemoney = (TextView) Comsumview.findviewbyid (R.id.tv_comsumemoney); comsumholder.useprevillage = ( TextView) Comsumview.findviewbyid (r.id.tv_useprevillage); Comsumholder.yuezhifu = (TextView) Comsumview.findviewbyid (R.id.tv_yuezhifu); Comsumholder.cash = (TextView) Comsumview.findviewbyid (R.id.tv_cash); Comsumholder.thisscore = (TextView) Comsumview.findviewbyid (R.id.tv_thisscore); Comsumholder.extrareward = (TextView) Comsumview.findviewbyid (R.id.tv_extrareward); Comsumview.settag ( Comsumholder); convertview = Comsumview;} else {Comsumholder = (Comsumviewholder) Convertview.gettag ();} ComsumHolder.branchnameCom.setText (Dateformatutil.formatdate (long.valueof (datalist.get (position). getmr_ Createtime ())) + "" "+ Record.getbranch_name ());//consumption time and branch ComsumHolder.comsumemoney.setText (Record.getpay_money ()); /Consumption amount ComsumHolder.useprevillage.setText (Record.getcoupon ());//Use Privileged ComsumHolder.yuezhifu.setText ( Record.getmember_money ());//Balance Payment ComsumHolder.cash.setText (Record.getcash ());// Cash Payment ComsumHolder.thisscore.setText (Record.getpoint ());//This time integral ComsumHolder.extrareward.setText (Record.getbonus ()  );//Bonus Bonus} else if (Currenttype = = type_charge) {Chargeviewholder Chargeholer = null;if (Convertview = = null) {Chargeholer = new Chargeviewholder (); Chargeview = Layoutinflater.from (Mcontext). Inflate (R.layout.traderecord_item_chongzhi, NULL); Chargeholer.branchnamecha = (TextView) ChargeviEw.findviewbyid (r.id.tv_branchname_charge); Chargeholer.prestoremoney = (TextView) Chargeview.findviewbyid (R.id.tv _prestoremoney); Chargeholer.extrasmoney = (TextView) Chargeview.findviewbyid (R.id.tv_extrasmoney); Chargeholer.totalmoney = (TextView) Chargeview.findviewbyid (R.id.tv_totalmoney); Chargeview.settag (ChargeHoler); Convertview = Chargeview;} else {Chargeholer = (Chargeviewholder) Convertview.gettag ();} ChargeHoler.branchnameCha.setText (Dateformatutil.formatdate (long.valueof (datalist.get (position). getmr_ Createtime ())) + "" "+ Record.getbranch_name ());//consumption time and branch//ChargeHoler.prestoremoney.setText (record.getprestore_ Money () +//"Yuan");//Deposit ChargeHoler.extrasmoney.setText (Record.getmember_money () + "Yuan");// Balance ChargeHoler.totalmoney.setText (Record.getmember_money () + "Yuan");//Total}return Convertview;}

This is the whole effect of the implementation process


Iv. Summary

In fact, for the ListView item to set a different layout file, to achieve the above effect, the steps are as follows;

1. Write different layout files for different item, set the unified JavaBean class

2, Inherit Baseadapter class, implement Getitemviewtype (int position) and Getviewtypecount () method, according to these two methods, set different tags for item, that is, different type

3. In the GetView method, use the Getitemviewtype (position) method to get the current type, and then load the different item layout files according to the different type types.

4. Some of the other ListView optimizations are not very different from the general 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.