Listview programming: how to optimize custom Adapter

Source: Internet
Author: User

To use a custom adapter, We need to optimize the custom adapter class!

In the end, the getview method is used to optimize the callback method.


Listview programming: What is the secret of the adapter? The blog briefly introduces how to customize an adapter and precautions.


But .......

If you want to program like listview: What is the secret of adapter? If you write the program like the sample code in, it is estimated that the Code will be written by the boss BS!


Then, further optimization work is carried out based on Google Io recommendations, apidemo code, and personal opinions.


Note: This blog uses layout files andListview programming: What is the secret of the adapter?The appendix is consistent.


Organize code to prepare for Optimization


Activity Code

Package mark. zhang; import Java. util. arraylist; import android. app. listactivity; import android. OS. bundle; public class fileactivity extends listactivity {public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // Add the module arraylist <string> arrays = new arraylist <string> (); For (INT I = 0; I <30; I ++) {arrays. add ("" + I);} // instantiate the custom adapter fileviewadapter adapter = new fileviewadapter (this, arrays); // set the adapter setlistadapter (adapter );}}

Fileviewadapter code

Package mark. zhang; import Java. util. arraylist; 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. imageview; import android. widget. textview; public class fileviewadapter extends baseadapter {private layoutinflater Inflater = NULL; private arraylist <string> Arrays = NULL; Public fileviewadapter (context, arraylist <string> arrays) {This. arrays = arrays; Inflater = layoutinflater. from (context) ;}@ overridepublic int getcount () {log. D ("mark", "getcount () is invoked! "); // Return the number of items to be displayed. // This is the number provided by the outside world, which is different from the previous generation. Return arrays. size () ;}@ overridepublic object getitem (INT position) {log. D ("mark", "getitem () is invoked! "); Return position ;}@ overridepublic long getitemid (INT position) {log. D (" mark "," getitemid () is invoked! "); Log. D ("mark", "position =" + position); Return position ;}@ overridepublic view getview (INT position, view convertview, viewgroup parent) {log. D ("mark", "getview () is invoked! "); View v = Inflater. inflate (R. layout. custom_fileview, null); (imageview) v. findviewbyid (R. id. image_pic )). setimageresource (R. drawable. file); (textview) v. findviewbyid (R. id. text_content )). settext ("FILENAME"); Return v ;}}


Running effect:

OK. Reorganizing the code is a preparation for the following optimization.


In the following optimization scheme, the getview method of fileviewadapter is optimized, and other code remains unchanged.


Before optimization, you should first understand one problem:Three parameters of the getview Method


The getview method has three parameters. For the meanings of each parameter, see the sdk api documentation.


Modify the code (that is, modify the log output ):

@Overridepublic View getView(int position, View convertView, ViewGroup parent) {Log.d("mark", "getView() is invoked!" + "position = " + position + ","+ "convertView = " + convertView + "," + "parent = " + parent);View v = inflater.inflate(R.layout.custom_fileview, null);((ImageView) v.findViewById(R.id.image_pic)).setImageResource(R.drawable.file);((TextView) v.findViewById(R.id.text_content)).setText("fileName");return v;}

Run the app and print the following information:


It can be seen that the getview method has been called for 16 (0-15) times, not 30 times.


Take a closer look at the simulator to know the currently displayed item

Is 16 (there is another incomplete display, it should be 17, as can be seen from the print information below.

Not 30.


Then, slide the scroll bar in the current view and try it.




It can be seen that the getview method is indeed called 30 times (0-29 ).
You can also find that convertview is not null in the print information displayed in the (scroll.

Scroll the scroll bar to the top again and find that convertview is not null in the print information.


In other words:

Use the convertview parameter instead of re-creating a temporary variable view in the getview method,

This can reduce the burden on virtual machines (recovery) and improve efficiency.


Solution 1 _ optimization code: Use convertview


@ Override
Public View getview (INT position, view convertview, viewgroup parent ){
Log. D ("mark", "getview () is invoked! "+" Position = "+ Position + ","
+ "Convertview =" + convertview + "," + "parent =" + parent );
If (convertview = NULL ){
Convertview = Inflater. Inflate (R. layout. custom_fileview, null );
}


(Imageview) convertview. findviewbyid (R. Id. image_pic ))
. Setimageresource (R. drawable. File );
(Textview) convertview. findviewbyid (R. Id. text_content ))
. Settext ("FILENAME ");

Return convertview;
}

It can be seen that only convertview = NULL is true (the test above shows when convertview is null ),

To create a view object.

If you are interested, you can run the app again to see that the app is rolling from the bottom to the top again,

Several times, you will find that you rarely create view objects, but reuse existing view objects.

There is another way to optimize the code, not to mention the best but at least even better (recommended by Google )!

Solution 2 _ optimization code: Hold one

In the apidemo provided by Android (list14.java), viewholder is used,

Therefore, viewholder is neither an API provided by Android nor a strange thing.


@ Override
Public View getview (INT position, view convertview, viewgroup parent ){
Log. D ("mark", "getview () is invoked! "+" Position = "+ Position + ","
+ "Convertview =" + convertview + "," + "parent =" + parent );

Viewholder vholder = NULL;

If (convertview = NULL ){
Convertview = Inflater. Inflate (R. layout. custom_fileview, null );
// Construct a viewhodler object
Vholder = new viewholder ();
Vholder. PIC = (imageview) convertview. findviewbyid (R. Id. image_pic );
Vholder. content = (textview) convertview
. Findviewbyid (R. Id. text_content );
// Set the tag
Convertview. settag (vholder );
} Else {
Vholder = (viewholder) convertview. gettag ();
}
Vholder. PIC. setimageresource (R. drawable. File );
Vholder. content. settext ("FILENAME ");
Return convertview;
}

Viewholder is a static internal class of fileviewadapter.

Static class viewholder {
Textview content;
Imageview PIC;
}

The key advantage of viewholder is that it caches the view of the displayed data and accelerates the UI response speed.


So far, it seems that the optimization work has been OK. In fact,

Another small problem is that the image resources used by imageview need to be preprocessed.

The complete code of fileviewadapter is as follows:

Package mark. zhang; import Java. util. arraylist; import android. content. context; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. util. log; import android. view. layoutinflater; import android. view. view; import android. view. viewgroup; import android. widget. baseadapter; import android. widget. imageview; import android. widget. textview; public class fileviewadapter extends baseada Pter {private layoutinflater Inflater = NULL; private arraylist <string> arrays = NULL; private bitmap showicon = NULL; Public fileviewadapter (context, arraylist <string> arrays) {This. arrays = arrays; Inflater = layoutinflater. from (context); // process the image source showicon = bitmapfactory. decoderesource (context. getresources (), R. drawable. file) ;}@ overridepublic int getcount () {// log. D ("mark", "getcount () is in Voked! "); // Return the number of items to be displayed. // This is the number provided by the outside world, which is different from the previous generation. Return arrays. size () ;}@ overridepublic object getitem (INT position) {// log. D ("mark", "getitem () is invoked! "); Return position ;}@ overridepublic long getitemid (INT position) {// log. D (" mark "," getitemid () is invoked! "); // Log. D ("mark", "position =" + position); Return position ;}@ overridepublic view getview (INT position, view convertview, viewgroup parent) {log. D ("mark", "getview () is invoked! "+" Position = "+ Position +", "+" convertview = "+ convertview +", "+" parent = "+ parent); viewholder vholder = NULL; if (convertview = NULL) {convertview = Inflater. inflate (R. layout. custom_fileview, null); // create a viewhodler object vholder = new viewholder (); vholder. PIC = (imageview) convertview. findviewbyid (R. id. image_pic); vholder. content = (textview) convertview. findviewbyid (R. id. text_content); // set tagconvertview. settag (vholder);} else {vholder = (viewholder) convertview. gettag ();} // set the bit to invalid vholder. PIC. setimagebitmap (showicon); vholder. content. settext ("FILENAME"); Return convertview;} static class viewholder {textview content; imageview PIC ;}}

Finally, we need to set the properties of the listview control in the layout file:


Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"

For details about how listview works (recycler) and how to further optimize listview, refer

Http://mzh3344258.blog.51cto.com/1823534/889879

Download Google Io documentation

Http://download.csdn.net/detail/androidbluetooth/3783925










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.