Android Learning Note 24 ListView List View II

Source: Internet
Author: User

Android Learning Note 24 ListView List View II

In the previous article we introduced the simple implementation of several commonly used adapters and the simple use of the ListView, in this article, we introduce the ListView optimization and some other problems.

ListView Optimization Method One

In the ListView, our most common is custom adapter, in our custom adapter, we need to implement two more important methods GetCount () and GetView (), the former is responsible for calculating the total item number of the ListView, The latter is the number of times that the GetView () method will be called when the item is generated and how many item it has. The GetView () method will re-inflate a view to return each time it is called, but for the ListView, you only need to keep the maximum number of view that can be displayed, and the new view can reuse the missing view. The ListView provides us with a reusable view object, which in the GetView () method has a parameter view, which is the view object that can be reused. When the parameter view is NULL, we need to inflate a view, and when it is not NULL, we can return it directly. For example:

 @Overridepublic View getView(int i, View view, ViewGroup viewGroup) {    ViewHolder viewHolder;    //view为空的时候,inflate一个新的view    if (view == null) {        view = LayoutInflater.from(context).inflate(R.layout.item_base_adapter, null);        viewHolder = new ViewHolder();        viewHolder.tv_base_adapter = (TextView) view.findViewById(R.id.tv_base_adapter);        view.setTag(viewHolder);    } else {        viewHolder = (ViewHolder) view.getTag();    }    viewHolder.tv_base_adapter.setText(datas[i]);    //不为空,复用view    return view;}
ListView Optimization Method Two

The above describes the optimization of view multiplexing so that we can eliminate the need for each item to inflate a new view, which can be reused to reduce memory overhead. Here we describe an essential operation in each of the Androidapp, get the control handle, simply to get the ID. In the ListView, we inflate a view, there is also need to get the component ID, we can use Viewholder to achieve the optimization:

The specific idea is that we store the controls we need in Viewholder, and when the view is null, we need to inflate a new view, and we'll also new a Viewholder class object, and assign the result of Findviewbyid to the corresponding member variable in Viewholder, we can call the view in the Settag () method to bind Viewholder and view together. When view is not NULL, the Gettag () method is used to remove the Viewholder object so that the member variable in the Viewholder can be obtained and the Findviewbyid method is no longer required. For example:

@Overridepublic View getView(int i, View view, ViewGroup viewGroup) {    ViewHolder viewHolder;    if (view == null) {        view = LayoutInflater.from(context).inflate(R.layout.item_base_adapter, null);        //view为空,new一个ViewHolder对象        viewHolder = new ViewHolder();        //获取到ViewHolder对象中成员变量的id        viewHolder.tv_base_adapter = (TextView) view.findViewById(R.id.tv_base_adapter);        //调用setTag方法,将ViewHolder绑定到中        view.setTag(viewHolder);    } else {        //view不为空,调用getTag方法,取出保存的ViewHolder对象        viewHolder = (ViewHolder) view.getTag();    }    viewHolder.tv_base_adapter.setText(datas[i]);    return view;}static class ViewHolder {    TextView tv_base_adapter;}
ListView Optimization Method Three

The two optimization methods of the ListView are described above, and the second optimization efficiency is based on the analysis of Google's official documents, which optimizes the efficiency of around 5%. The third optimization method is described below.

In our actual development, the ListView display data are loaded in the network, if the network is better, can be loaded all the data at once, so that the user experience is OK, if the network is not good, then load the data takes a long time, the user experience is not good. In addition, we know that the memory allocated by the virtual machine for each process is limited, and if you load too much data there will be a memory overflow situation. In order to solve these two problems, we can use the partial load method, but the batch loading still does not solve the problem completely. If I have 100,000 data that needs to be loaded, and there may be an oom problem with batch loading, then we need to load the data page by page and load it in batches, so the user experience will be better.

Some problems with the ListView and fix the ListView focus issue

In some cases, we need to add a button, EditText, checkbox and other controls to the ListView item, which involves the issue of focus acquisition. We added a button to the ListView item, and click Find, we can't trigger the Onitemclick and Onitemlongclick methods, which is the focus of the ListView is blocked. The solution is also simple:

Set the android:focusable= "false" property to the control that intercepts the ListView focus or Code call Setfocusable (FALSE) to guard against it. Another way is to set the android:descendantfocusability= "Blocksdescendants" property on the root node of the item layout, which has three optional values

    • Beforedescendants:viewgroup takes precedence over its subclass control and gets to focus
    • Afterdescendants:viewgroup gets focus only if its subclass control does not need to get focus
    • Blocksdescendants:viewgroup overrides the subclass control and gets the focus directly

This is a workaround for the ListView focus issue.

ListView Data Update Issues

Start by implementing a simple ListView

Layout 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=" match_parent "android:orientation=" vertical " ><linearlayout android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_marg inleft= "10DP" android:layout_margintop= "10DP" android:orientation= "horizontal" > <button android:id= " @+id/btn_add_one "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:te        xt= "Inserting a data"/> <button android:id= "@+id/btn_add_on_position" android:layout_width= "Wrap_content"    android:layout_height= "Wrap_content" android:text= "insert a piece of data at a specific location"/></linearlayout><linearlayout Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:layout_marginbottom= "10DP" Andro id:layout_marginleft= "10DP" Android:orientation= "Horizontal" > <button android:id= "@+id/btn_delete_one" android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Delete from Object"/> <button android:id= "@+id/btn_delete _on_position "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:text=" Delete "/> <button android:id=" @+id/btn_delete_all "android:layout_width=" Wrap_content "based on location" Android oid:layout_height= "wrap_content" android:text= "Delete all data"/></linearlayout><listview android:id= "@+id/l V_data "android:layout_width=" match_parent "android:layout_height=" Match_parent "/></linearlayout>

Item Layout Code:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="10dp"android:gravity="center_vertical"android:orientation="horizontal"><ImageView    android:id="@+id/iv_icon"    android:layout_width="40dp"    android:layout_height="40dp"    android:src="@drawable/icon" /><TextView    android:id="@+id/tv_data_text"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_centerVertical="true"    android:layout_marginLeft="5dp"    android:layout_toRightOf="@id/iv_icon"    android:text="加载出来的数据"    android:textSize="18sp" /></RelativeLayout>

The item here is simple, it is directly a picture and a text

Activity code:

Package Com.example.listviewdemo.activity;import Android.os.bundle;import android.support.annotation.Nullable; Import Android.support.v7.app.appcompatactivity;import Android.view.view;import Android.widget.button;import Android.widget.listview;import Com.example.listviewdemo.mydata;import Com.example.listviewdemo.r;import Com.example.listviewdemo.adapter.dataadapter;import java.util.arraylist;import java.util.List;/** * Created by Devin On 2016/7/11. */public class Dataupactivity extends appcompatactivity {private button btn_add_one;private button btn_add_on_position; Private button btn_delete_one;private button btn_delete_on_position;private button btn_delete_all;private ListView lv_ Data;private DataAdapter adapter;private list<mydata> datas;private int flag = 1; @Overrideprotected void OnCreate (    @Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_data);    Btn_add_one = (Button) Findviewbyid (R.id.btn_add_one); Btn_add_on_position = (Button) Findviewbyid (r.id.btn_add_on_position);    Btn_delete_one = (Button) Findviewbyid (R.id.btn_delete_one);    Btn_delete_on_position = (Button) Findviewbyid (r.id.btn_delete_on_position);    Btn_delete_all = (Button) Findviewbyid (R.id.btn_delete_all);    Lv_data = (ListView) Findviewbyid (r.id.lv_data);    Datas = new arraylist<> ();    adapter = new DataAdapter (this, datas);  Lv_data.setadapter (adapter); }}

Custom Adapter Code:

Package Com.example.listviewdemo.adapter;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.ImageView ; Import Android.widget.textview;import Com.example.listviewdemo.mydata;import Com.example.listviewdemo.r;import Java.util.arraylist;import java.util.list;/** * Created by Devin on 2016/7/11. */public class DataAdapter extends Baseadapter {private list<mydata> datas;private Context mcontext;public    DataAdapter (Context mcontext, list<mydata> datas) {this.mcontext = Mcontext; This.datas = datas;} @Overridepublic int GetCount () {return datas.size ();} @Overridepublic Object getItem (int i) {return i;} @Overridepublic long Getitemid (int i) {return i;}    @Overridepublic View GetView (int i, view view, ViewGroup viewgroup) {Viewholder viewholder; if (view = = null) {view = Layoutinflater.from (Mcontext). Inflate (R.layout.item_data, NULL);        Viewholder = new Viewholder ();        Viewholder.tv_data_text = (TextView) View.findviewbyid (R.id.tv_data_text);        Viewholder.iv_icon = (ImageView) View.findviewbyid (R.id.iv_icon);    View.settag (Viewholder);    } else {Viewholder = (Viewholder) view.gettag ();    } viewHolder.iv_icon.setImageResource (Datas.get (i). Geticonid ());    ViewHolder.tv_data_text.setText (Datas.get (i). GetContent ()); return view;}    private static class Viewholder {TextView tv_data_text; ImageView Iv_icon;}}

And there's a normal bean.

package com.example.listviewdemo;/** * Created by Devin on 2016/7/11. */public class MYData {private int iconId;private String content;public MYData() {}public MYData(int iconId, String content) {    this.iconId = iconId;    this.content = content;}public int getIconId() {    return iconId;}public void setIconId(int iconId) {    this.iconId = iconId;}public String getContent() {    return content;}public void setContent(String content) {    this.content = content;}@Overridepublic String toString() {    return "Data{" +            "iconId=" + iconId +            ", content=‘" + content + ‘\‘‘ +            ‘}‘;}}

Thus, the effect of our operation is:

There is no item shown, because we add an empty list to the adapter, and then we implement the button's event and the specific update listview

Insert a piece of data

Add this method to the adapter:

/** * 添加数据 * * @param myData */public void addData(MYData myData) {    if (datas == null) {        datas = new ArrayList<>();    }    datas.add(myData);    notifyDataSetChanged();}

To implement a click event in the activity:

btn_add_one.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            MYData data = new MYData(R.drawable.icon, "这是添加的数据~~~~~~X" + flag);            adapter.addData(data);            flag++;        }    });

Can be implemented in the ListView to add a piece of data, the concrete will be in the following uniform attached

Inserts a piece of data at the specified location

Add the following method to the adapter:

/** * 在指定位置添加数据 * * @param position * @param myData */public void addData(int position, MYData myData) {    if (datas == null) {        datas = new ArrayList<>();    }    datas.add(position, myData);    notifyDataSetChanged();}

To implement a button's Click event:

btn_add_on_position.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            MYData data = new MYData(R.drawable.icon, "这是添加的数据~~~~~~X" + flag);            adapter.addData(3, data);        }    });

Can be done at the specified location to add a piece of data, this is just a simple implementation, if there is not so much data in the list, there will be an array subscript out of bounds error

Delete data based on object

Add the following method to the adapter:

/** * 根据对象删除数据 * * @param myData */public void removeData(MYData myData) {    if (datas != null) {        datas.remove(myData);    }    notifyDataSetChanged();}

To implement a button's Click event:

btn_delete_one.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            MYData data = datas.get(2);            adapter.removeData(data);        }    });

Here is simply the deletion of the subscript 3 of the data, if the ListView is less than 3, there will be an array subscript out of bounds error

Delete data based on location

Add the following method to the adapter:

/** * 根据位置删除数据 * * @param position */public void removeData(int position) {    if (datas != null && position <= datas.size()) {        datas.remove(position);    }    notifyDataSetChanged();}

To implement a button's Click event:

btn_delete_on_position.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            adapter.removeData(3);        }    });

Delete data at the specified location, you need to determine if there is an error

Delete all the data

Add the following method to the adapter:

/** * 清除所有的数据 */public void removeAll() {    if (datas != null) {        datas.clear();    }    notifyDataSetChanged();}

To implement a button's Click event:

btn_delete_all.setOnClickListener(new View.OnClickListener() {        @Override        public void onClick(View view) {            adapter.removeAll();        }    });

Finally attached:

The data update problem for the ListView is implemented here, but there are still some small problems, such as a blank when there is no data, and the user experience is not very good. Can be overridden according to the data returned by the server update interface. There is no implementation here. In the next section we introduce the implementation of the ListView multi-layout, such as QQ chat interface.

Android Learning Note 24 ListView List View II

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.