Android Beginner Learning ListView

Source: Internet
Author: User
Tags pear

When the list of Android data is displayed, the ListView is usually used, so list the

1, custom ListView with System

First, create a ListView in the XML file

   <listview         android:id= "@+id/list_view"        android:layout_width= "match_parent"        android:layout_height = "Match_parent"              ></ListView>
Then set up the data in the Mainavtivity, where the data is generally prepared in advance,is usually downloaded from the Web or extracted from the database .

The array is used here to provide a set of data, but not directly to the ListView, which requires the use of many of the Android adapters to operate (for data from the database with the adapter is not the same, here first regardless)
Private string[] data = {"Apple", "Banana", "Orange", "Watermelon",                 "Pear", "Grape", "Pineapple", "Strawberry", "C Herry "," Mango "}; @Override     protected void onCreate (Bundle savedinstancestate) {            super.oncreate ( Savedinstancestate);           Requestwindowfeature (Window. Feature_no_title);           Setcontentview (r.layout. Activity_main);           arrayadapter<string> adapter = new Arrayadapter<string> (                      Mainactivity.this, Android. R.layout.simple_list_item_1, data);           ListView ListView = (ListView) Findviewbyid (R.id.list_view);            Listview.setadapter (adapter);     }
here's Android. R.layout. simple_list_item_1 is the ID of the list subkey , which is an Android built-in layout file with only one textview, so that the data can be displayed simply The function used is arrayadapter (context context , int Textviewresourceid, List<T > objects ) to assemble the data Setadapter transfer the configured adapter inFor adapter issues, the Android Development manual is mainly about three types ofArrayadapter,simpleadapter,simplecursoradapterat the same time there is a point to note that adapter and Adapterview is not the same concept,adapter is the link between data and Adapterview Bridge, the specific difference can be self-degree In this case, the above code completes the basic list function, but these lists are simply the text of each display
obviously such a list does not meet the requirements, then you can define an adapter to connect the data and view
2, customizing the ListView interfaceobviously the above is too monotonous time limit does not, for this we first establish fruit class, save property name and imageIDYou can also create a new layout file Fruit_item.xmlput ImageView textview display pictures and textThe next is to make a custom adapter that inherits the arrayadapter<fruit> of the adapter justthe exact XML file creation is also very simple
<imageview     android:id= "@+id/fruit_image"    android:layout_width= "wrap_content"    android:layout_ height= "Wrap_content"    /><textview     android:id= "@+id/fruit_name" android:layout_width= "Wrap_    Content "    android:layout_height=" wrap_content "    android:layout_gravity=" center "    Android:layout_ marginleft= "10DP"    />


Create a class that inherits the adapter class

public class Fruitadapter extends arrayadapter<fruit> {private int resourceId; Public Fruitadapter (context context, int resource, list<fruit> objects) {Super (context, resource, objec            TS);     TODO auto-generated constructor stub resourceid= resource;  } @Override public View getView (int position, view Convertview, ViewGroup parent) {//TODO auto-generated method Stub/*return Super.getview (Position, convertview, parent); *//Get current FRU        It instance Fruit fruit= GetItem (position);                 View view= Layoutinflater.from (GetContext ()). Inflate (resourceId, NULL);           ImageView fruitimage= (ImageView) View.findviewbyid (r.id. fruit_image);                       TextView fruitnmae= (TextView) View.findviewbyid (r.id. fruit_name);            Fruitimage.setimageresource (Fruit.getimageid ());            Fruitnmae.settext (Fruit.getname ());             return view; } 

The first is to rewrite a set of constructors for the parent class, passing in the context, the ID of the ListView Child layout, and the data.It also overrides the GetView method, which is called when each child is scrolled into the screen.In the GetView method, obtain an instance of the current fruit and then use theLayoutinflater Loads the incoming layout for the child, then calls the Findviewbyid () method to get to the ImageView instance and TextView instance, and then sets the text and picture so that the custom adapter is completed. The last is to modify Mainactivity
public class Mainactivity extends Activity {/*private string[] data = {"Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango"};*/private list<fruit> fruitlist = new      Arraylist<fruit> ();            @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);            /*requestwindowfeature (window.feature_no_title); */Setcontentview (r.layout. Activity_main); /*arrayadapter<string> adapter = new Arrayadapter<string> (Mainactivity.this, Android.           R.layout.simple_list_item_1, data);           ListView ListView = (ListView) Findviewbyid (R.id.list_view);       Listview.setadapter (adapter); *//Initialization of fruit initfruit ();       Fruitadapter adapter= New Fruitadapter (mainactivity. This, R.layout.fruit_item, fruitlist);       ListView listview= (ListView) Findviewbyid (R.id.list_view); Listview.Setadapter (adapter); } private void Initfruit () {//TODO auto-generated method stub Fruit apple = new Fruit ("Apple"            , r.drawable.apple_pic);           Fruitlist.add (Apple);            Fruit banana = new Fruit ("banana", r.drawable.banana_pic);           Fruitlist.add (banana);            Fruit orange = new Fruit ("Orange", r.drawable.orange_pic);           Fruitlist.add (orange);            Fruit watermelon = new Fruit ("Watermelon", r.drawable.watermelon_pic);           Fruitlist.add (watermelon);            Fruit pear = new Fruit ("Pear", r.drawable. Pear_pic);           Fruitlist.add (pear);            Fruit grape = new Fruit ("Grape", r.drawable.grape_pic);           Fruitlist.add (grape);            Fruit pineapple = new Fruit ("Pineapple", r.drawable.pineapple_pic);           Fruitlist.add (pineapple);            Fruit Strawberry = new Fruit ("Strawberry", r.drawable.strawberry_pic);           Fruitlist.add (strawberry); FrUit cherry = new Fruit ("Cherry", r.drawable.cherry_pic);           Fruitlist.add (cherry);            Fruit mango = new Fruit ("Mango", r.drawable.mango_pic);     Fruitlist.add (Mango); }
The main is the ListView completes the initialization, and then produces a custom adapter for assembly data, passed to the ListView

on the problem of efficiency optimization currently our ListView is running at very low efficiency because of the Fruitadapter GetView ()
The layout is reloaded once each time in the method, which becomes a bottleneck for performance when the ListView is scrolling fast.
Carefully observed, the GetView () method also has a Convertview parameter, which is used to load the previously loaded
The layout is cached so that it can be reused later
the above action is to prevent the repeated drawing of the layout, while the reading of each control can also prevent the problem of repeated drawing, specific to the code, mainly modify the custom adapter class some methods
public class Fruitadapter extends arrayadapter<fruit> {private int resourceid;public Fruitadapter (Context context , int resource, list<fruit> objects) {Super (context, resource, objects);//TODO auto-generated constructor Stubreso Urceid=resource;}  @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {//TODO auto-generated method Stub/*return Super.getview (position, convertview, parent); *///Gets the current fruit instance fruit fruit= getItem (position);/* * Convertview is primarily to cache the previously loaded layout */view View; Viewholder Viewholder;             if (convertview==null) {view= layoutinflater.from (GetContext ()). Inflate (resourceId, NULL);             Viewholder=new Viewholder ();             Viewholder.fruitimage= (ImageView) View.findviewbyid (r.id.fruit_image); Viewholder.fruitname= (TextView) View.findviewbyid (r.id.fruit_name);   }else{view =convertview;viewholder= (Viewholder) View.gettag ();} /* ImageView fruitimage= (ImageView) View.findviewbyid (r.id.fruit_image); TextView fruitnmae= (TextvieW) View.findviewbyid (r.id.fruit_name); Fruitimage.setimageresource (Fruit.getimageid ()); FruitNmae.setText ( Fruit.getname ()); */viewholder.fruitimage.setimageresource (Fruit.getimageid ()); ViewHolder.fruitName.setText ( Fruit.getname ()); return view;} Class Viewholder{imageview Fruitimage; TextView fruitname;}}

The main is to add a Viewholder class to put the corresponding instance, and since Converview is stored in the layout cache, so in determining whether it is empty, you can judge whether the control needs to be drawn







Android Beginner Learning ListView

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.