Android Self-study course-listview from Jane into deep

Source: Internet
Author: User

The previous period of time to learn Recyclerview, found that the ListView has a more obvious feeling, so decided to take the inventory of the idea of the ListView, finishing after all after 5.0 popularity, the ListView still has its place. As always, we start from the simple. --standing on the shoulders of giants

Translated from: https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView# Using-a-basic-arrayadapter, may I understand not deep, translation eccentric, take me to knock several times, and then a few for everyone to share.

Using a arrayadapter with ListView

In the development of Android, we often use the ListView to present a set of vertical scrolling list requirements, when we populate the data with Adapter . The simplest adaper is arrayadapter, because the adapter transforms the ArrayList object into a View list, which is loaded into the ListView container.

                  

Row View Recycling

When using adapter and ListView , we need to make sure we understand how the view recycling mechanism works.

When your ListView is contacted with adapter, the adapter will instantiate each row list until the ListView is populated with sufficient items (items fill the total height of the ListView), in which case There will be no redundant list of objects to be created in memory.

Instead, when the user scrolls down the list, items that leave the screen are saved in memory for later use , and each new list of rows enters the screen, and the list of rows saved in memory is reused. so, even with a list of 1000 lists, a view that requires only about 7 rows of tables needs to be instantiated or saved in memory, which is an intuitive overview of recycling:

                

This is another collection of view-related graphs.

                 

See another ListView for this guide (individuals who feel there is a better choice, will later write a blog) and see how this works to optimize the performance of your list.

Using a Basic Arrayadapter

In order to use the basic arrayadaper, we just need to instantiate a adapter and connect the adapter to the ListView. In the first step, we initialize a adapter.

New Arrayadapter<string> (this, Android. R.layout.simple_list_item_1,items);

Arrayadapter needs to declare item when it is converted to view type (a String in this case), which in turn receives three parameters: context (activity instance), XML item Layout,and the array date. Note that we have chosen

Simple_list_item_1, she is a simple use of TextView as a layout for every items.

Now, we need this adapter to connect to the ListView to populate,

ListView ListView = (ListView) Findviewbyid (R.id.lvitems); Listview.setadapter (itemsadapter);

By default, this would now convert each item in the data array to a view by calling on the item and then toString assigning t He result as the value of a TextView (Simple_list_item_1.xml) is displayed as the row for that data item. (translation does not come, I feel it, ask good people to guide the translation). If your application requires more complex transformations in item and view, then we need to create a custom arrayadapter to replace it.

Using a Custom arrayadapter (Prepare data template, view template)

When we want to show you a series of custom lists in the list, we need to give each items a custom XML layout file that we use. In order to complete this step, we are going to create a custom Arrayadapter class. See this repo for the source code.

In the first step, we often define a template to describe the data needed for each item in a list.

Defining the Model

Create a Java object to define some fields, for example, the User class

 Public class User {    public  String name;      Public String hometown;      Public User (string name, string hometown) {       this. Name = name;         this. Hometown = hometown;    }}

Creating the View Template

Next, we need to create an XML layout file that represents the template for each item, Res/layout/item_user.xml:

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >    <TextViewAndroid:id= "@+id/tvname"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Name" />   <TextViewAndroid:id= "@+id/tvhome"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "Hometown" /></LinearLayout>

Defining the Adapter

Next, we need to define adapter and describe the process by which the Java object is transformed into view (in the GetView method). The tender method is as follows (without any caching):

 Public classUsersadapterextendsArrayadapter<user> {     PublicUsersadapter (context context, arraylist<user>users) {       Super(Context, 0, users); } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {       //Get The data item for this positionUser User =GetItem (position); //Check If an existing view is being reused, otherwise inflate the view       if(Convertview = =NULL) {Convertview= Layoutinflater.from (GetContext ()). Inflate (R.layout.item_user, parent,false); }       //Lookup View for data populationTextView Tvname =(TextView) Convertview.findviewbyid (r.id.tvname); TextView Tvhome=(TextView) Convertview.findviewbyid (r.id.tvhome); //Populate the data into the template view using the data objectTvname.settext (User.Name);       Tvhome.settext (User.hometown); //Return The completed view to render in screen       returnConvertview; }}

Adapter has a construction and GetView () method to describe the transition between data items and views.

GetView () is a method that returns the actual view that is used as a row within a ListView in a specific location.

Attaching the Adapter to a ListView

Now, we can use that adapter in the activity to show an array of items embedded in the ListView:

// Construct the data source New Arraylist<user>(); // Create the adapter to convert the array to views New Usersadapter (this, arrayofusers); // Attach the adapter to a ListView ListView ListView = (ListView) Findviewbyid (R.id.lvitems); Listview.setadapter (adapter);

At the moment, the ListView control is now successfully bound to the user array data.

Populating Data into ListView

Once the adapter is connected, items are automatically populated into the ListView, based on the contents of the array.

We can add a new item to the adapter:

// ADD item to adapter New User ("Nathan", "San Diego"); Adapter.add (newuser); // Or even append an entire new collection // fetching some data, data have now returned // If data is JSON, convert to ArrayList of User objects. Jsonarray Jsonarray = ...; ArrayList<User> newusers = User.fromjson (jsonarray) Adapter.addall (newusers);

This will append the new items to the list. We can also clear all the list at any time, just one sentence:

Adapter.clear ();

Now we can add, delete, modify the user and the items in the ListView will automatically make the corresponding reflection.

Constructing Models from External source (build model from external source)

to create a model instance, we might load data from an external source (that is, the database or the rest JSON API), so we should create 2 additional methods in each model that allow you to build a list or a single item if the data is from the JSON API .

 Public classUser {//Constructor to convert JSON object into a Java class instance     PublicUser (Jsonobject object) {Try {             This. Name = object.getstring ("name");  This. Hometown = object.getstring ("Hometown"); } Catch(jsonexception e) {e.printstacktrace (); }    }    //Factory method to convert an array of JSON objects into a list of objects//User.fromjson (jsonarray);     Public StaticArraylist<user>Fromjson (Jsonarray jsonobjects) {ArrayList<User> users =NewArraylist<user>();  for(inti = 0; I < jsonobjects.length (); i++) {               Try{Users.add (NewUser (Jsonobjects.getjsonobject (i))); } Catch(jsonexception e) {e.printstacktrace (); }          }          returnusers; }}

For more details, check the on converting JSON into a model. If you is not using a JSON source for your data, you can safely skip this step.

(I've never met, I feel like I'm important)

Improving performance with the Viewholder Pattern

To improve performance, we should modify the custom adapter by applying the Viewholder pattern which speeds up th E population of the ListView considerably by caching view lookups for smoother, faster item loading:

 Public classUsersadapterextendsArrayadapter<user> {    //View Lookup Cache    Private Static classViewholder {TextView name;    TextView home; }     PublicUsersadapter (context context, arraylist<user>users) {       Super(context, r.layout.item_user, users); } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {       //Get The data item for this positionUser User =GetItem (position); //Check If an existing view is being reused, otherwise inflate the viewViewholder Viewholder;//View lookup cache stored in tag       if(Convertview = =NULL) {Viewholder=NewViewholder (); Layoutinflater Inflater=Layoutinflater.from (GetContext ()); Convertview= Inflater.inflate (R.layout.item_user, parent,false); Viewholder.name=(TextView) Convertview.findviewbyid (r.id.tvname); Viewholder.home=(TextView) Convertview.findviewbyid (r.id.tvhome);       Convertview.settag (Viewholder); } Else{Viewholder=(Viewholder) Convertview.gettag (); }       //Populate the data into the template view using the data objectViewHolder.name.setText (User.Name);       ViewHolder.home.setText (User.hometown); //Return The completed view to render in screen       returnConvertview; }}

In this pest, we used a private static class calledViewHolder。在实践当中,调用FindViewById()是真的非常慢,如果你的adapter每次都调用他,为你的每一个行列都去调用她,你会很快发现将会出现性能问题。而ViewHolder这个类所做的事情就是缓存调用FindViewById()这个方法。一旦你的ListView到达它可以在屏幕上显示的行的最大数量,Android会非常聪明的回收这些行的View。我们测试一下,如果既if(convertView == Null)之后,一个View(Item的视图)被回收。如果不是Null的话,我们就有可以使用的回收后的View,并且我们可以改变她的值,否则我们需要擦魂归一个新的行的View。The magic behind this is the setTag() method which lets us attach an arbitrary object onto a View object, which is how we save the already inflated View for future reuse.(在这背后的魔法就是setTag()方法,这个方法能够让我们附属任意的对象到View对象之上,这就是我们如何保存已经实例化的View,供以后使用。

Beyond viewholders

customizing Android ListView Rows by subclassing describes a strategy for obtaining instances of the child views using a Simil AR approach as a viewholder but without the explicit Viewholder subclass.

References
    • http://lucasr.org/2012/04/05/performance-tips-for-androids-listview/
    • http://www.doubleencore.com/2013/05/layout-inflation-as-intended/
    • http://www.bignerdranch.com/blog/customizing-android-listview-rows-subclassing/

Data Lookup section:

Http://www.cnblogs.com/xiangtailiang/p/3379543.html

Http://www.javacodegeeks.com/2013/09/android-viewholder-pattern-example.html

Http://www.codeofaninja.com/2013/09/android-listview-with-adapter-example.html

Http://stackoverflow.com/questions/4145602/how-to-implement-a-view-holder

http://stackvoid.com/

Android Self-study course-listview from Jane into deep

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.