Android Learning Summary (13) ———— ListView Simple usage

Source: Internet
Author: User

First, the basic concept of the ListView

Of all the common native controls on Android, the most complicated usage should be the ListView, which is designed to handle a lot of content elements that the phone screen cannot display. The ListView can use the form of a list to present content, and the content beyond the screen can be moved to the screen by swiping through the finger. Even if you load very much data in the ListView, such as hundreds or even more, the ListView will not crash, and the memory used by the program will not grow as our fingers swipe to browse more data.

Second, the sample code

Define an entity class that is the appropriate type for the ListView adapter, as shown in the following code:

 Packagecom.nyl.listviewtest; Public classSkincare {PrivateString name; PrivateString efficacy;//Efficacy    Private intIcon//icons     PublicSkincare (string name, string efficacy,inticon) {         This. Name =name;  This. Efficacy =efficacy;  This. Icon =icon; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getefficacy () {returnefficacy; }     Public voidsetefficacy (String efficacy) { This. Efficacy =efficacy; }     Public intGetIcon () {returnicon; }     Public voidSetIcon (inticon) {         This. Icon =icon; }}

Customize the child layout of a ListView, as shown in the following code:

<?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= "120DP"android:orientation= "Horizontal" > <ImageView Android:id= "@+id/ivskincare"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"/> <LinearLayout android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Android:layout_marginleft= "10DP"android:orientation= "Vertical" > <TextView Android:id= "@+id/tvname"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:autolink= "All"android:textsize= "15DP"/> <TextView Android:id= "@+id/tvefficacy"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"/> </LinearLayout></LinearLayout>

Create a custom adapter that inherits from Arrayadapter and designates the generic as skincare as the entity class, creating a new Skincareadapter class with the code as follows:

 Packagecom.nyl.listviewtest;ImportAndroid.content.Context;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;Importjava.util.List;/*** Created by Administrator on 2017/3/9 0009.*/ Public classSkincareadapterextendsArrayadapter<skincare> {    Private intresourceId;  PublicSkincareadapter (Context context,intResource, list<skincare>objects) {        Super(Context, resource, objects); ResourceId=resource; }    /*** This method is called when each subkey is scrolled into the screen*/@Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {        //obtaining an instance of the current skincare through the GetItem () methodSkincare skincare =GetItem (position); /*** Improve the operation efficiency of the ListView, also can show better performance when rolling fast.*/        //use Viewholder to optimizeViewholder Viewholder; //judge Convertview to be empty        if(Convertview = =NULL) {            //if empty, use Layoutinflater to load the layoutConvertview = Layoutinflater.from (GetContext ()). Inflate (ResourceId,NULL); Viewholder=NewViewholder (); Viewholder.ivskincare=(ImageView) Convertview.findviewbyid (R.id.ivskincare); Viewholder.tvname=(TextView) Convertview.findviewbyid (r.id.tvname); Viewholder.tvefficacy=(TextView) Convertview.findviewbyid (r.id.tvefficacy); //store Viewholder in viewConvertview.settag (Viewholder); } Else {            //If the Convertview is not directly reused for null//Get Viewholder againViewholder =(Viewholder) Convertview.gettag (); }      /*//Use Layoutinflater to load the incoming layout (this is a very inefficient notation) view view = Layoutinflater.from (GetContext ()). Inflate (Resourceid,null        ); *//*** Call the View's Findviewbyid () method to get the layout control*//*Ivskincare = (ImageView) View.findviewbyid (R.id.ivskincare);        Tvname = (TextView) View.findviewbyid (r.id.tvname);        Tvefficacy = (TextView) View.findviewbyid (r.id.tvefficacy);        Call the Setimageresource () method to set the displayed picture Ivskincare.setimageresource (Skincare.geticon ());        Set the name of the skincare product Tvname.settext (Skincare.getname ()); Set the efficacy of skin care products Tvefficacy.settext (skincare.getefficacy ());*/ViewHolder.ivSkinCare.setImageResource (Skincare.geticon ());        ViewHolder.tvName.setText (Skincare.getname ());        ViewHolder.tvEfficacy.setText (Skincare.getefficacy ()); //returns the layout        returnConvertview; }        Static classViewholder {ImageView ivskincare; TextView tvefficacy;//the efficacy of skincare productsTextView Tvname;//Skincare Name        }}

The code is commented out in detail, but with a lot of explanation, and then write mainactivity, the code looks like this:

 Packagecom.nyl.listviewtest;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.AdapterView;ImportAndroid.widget.ListView;ImportAndroid.widget.Toast;Importjava.util.ArrayList;Importjava.util.List; Public classMainactivityextendsActivityImplementsAdapterview.onitemclicklistener {PrivateList<skincare> skincare =NewArraylist<>(); PrivateSkincareadapter Skincareadapter; PrivateListView LV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Initskincare (); //Initialize all skincare dataSkincareadapter =NewSkincareadapter (mainactivity. This, R.layout.skin_care,skincare); //Initializing layout controlsLV =(ListView) Findviewbyid (r.id.lv);        Lv.setadapter (Skincareadapter); //set the Setonitemclicklistener () method to register a listener for the ListViewLv.setonitemclicklistener ( This); }    /*** When a user clicks on any of the subkeys in the ListView, The Onitemclick () method is called back, in which case the I parameter can be used to determine which sub-item the user clicked on, and then get the appropriate skincare, and the name of the skincare product will be displayed by toast. */@Override Public voidOnitemclick (adapterview<?> adapterview, view view,intILongl) {Skincare SC=Skincare.get (i); Toast.maketext (mainactivity. This, Sc.getname (), Toast.length_short). Show (); }    /*** In the constructor, the name, effect, and image ID of the skincare product are passed in, and the created object is added to the skincare list .*/    Private voidInitskincare () {skincare Cleansingmilk=NewSkincare ("Facial Cleanser", "Basic cleaning", R.mipmap.skin_care);        Skincare.add (Cleansingmilk); Skincare Toner=NewSkincare ("Toner", "two times clean, deep hydrating", R.mipmap.skin_care);        Skincare.add (toner); Skincare Essence=NewSkincare ("Essence", "concentrate on solving a problem of the skin, from the inside to repair the skin", R.mipmap.skin_care);        Skincare.add (Essence); Skincare Eyecream=NewSkincare ("Eye Cream", "soothing eye fatigue, improving eye complexion"), R.mipmap.skin_care);        Skincare.add (Eyecream); Skincare Latex=NewSkincare ("Lotion", "add enough nourishment to the skin, activate skin cells, form collagen", R.mipmap.skin_care);        Skincare.add (latex); Skincare Facecream=NewSkincare ("Face Cream", "continue to replenish the skin with sufficient moisture and nutrients to keep the skin moist", R.mipmap.skin_care);        Skincare.add (Facecream); Skincare Mask=NewSkincare ("Mask", "clear pores, clear skin dirt, blackheads, dead cells", R.mipmap.skin_care);        Skincare.add (mask); Skincare Sunscreen=NewSkincare ("Isolation Cream", "comprehensive isolation of ultraviolet rays, dust, nicotine, computer radiation and other harmful substances on the skin damage", R.mipmap.skin_care);        Skincare.add (sunscreen); /*** The second type of notation*/        /*linkedlist<skincare> data = new linkedlist<> (); Data.add (New skincare ("Cleanser", "Basic cleaning", r.mipmap.skin_care));*/    }}

Run the program, and click on the essence, the effect is as follows:

  

Simple ListView knowledge to learn here, more knowledge point next section continue!

Android Learning Summary (13) ———— ListView Simple usage

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.