---
title: "动态更新listView"
author: "ping8080"
date: "2011-05-19T11:47:05Z"
tags: []
categories: ["移动开发"]
slug: "listview"
draft: false
lastmod: "2011-05-19T11:51:17Z"
id: 1050034
url: "https://ping8080.iteye.com/blog/1050034"
---

原文地址：[http://www.pocketdigi.com/20100827/75.html](http://www.pocketdigi.com/20100827/75.html)

### [notifyDataSetChanged() 动态更新ListView 通过 Handler AsyncTask两种方式](http://www.pocketdigi.com/20100827/75.html)

有时候我们需要修改已经生成的列表，添加或者修改数据，notifyDataSetChanged()可以在修改适配器绑定的数组后，不用重新刷新Activity，通知Activity更新ListView。今天的例子就是通过Handler AsyncTask两种方式来动态更新ListView.从今天起，每次学习的源代码都会打包上传，方便各位同学学习，注册帐号即可下载。  
布局main.xml:

```
1
2
3
4
5
6
7
8
9
10
11
12
```

```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<ListView  android:id="@+id/lv"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>
```

ListView列表布局playlist.xml:

```
1
2
3
4
5
6
7
8
```

```
<?xml version="1.0" encoding="utf-8"?>
<TextView 
  android:id="@+id/text1"
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="30px"
  android:textSize="18sp"
></TextView>
```

程序代码：

```
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
```

```
package com.pocketdigi;
 
import java.util.ArrayList;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
 
public class main extends Activity {
    /** Called when the activity is first created. */
	ListView lv;
	ArrayAdapter<String> Adapter;
	ArrayList<String> arr=new ArrayList<String>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        lv=(ListView)findViewById(R.id.lv);
    	arr.add("123");
    	arr.add("234");
    	arr.add("345");
    	Adapter = new ArrayAdapter<String>(this,R.layout.playlist, arr);
    	lv.setAdapter(Adapter);
    	lv.setOnItemClickListener(lvLis); 
    	editItem edit= new editItem();
    	edit.execute("0","第1项");//把第一项内容改为"第一项"
    	Handler handler=new Handler();
    	handler.postDelayed(add,3000);//延迟3秒执行
    }
    Runnable add=new Runnable(){
 
		@Override
		public void run() {
			// TODO Auto-generated method stub
			arr.add("增加一项");//增加一项
			Adapter.notifyDataSetChanged();	
		}   	
    };
    class editItem extends AsyncTask<String,Integer,String>{
		@Override
		protected String doInBackground(String... params) {
				arr.set(Integer.parseInt(params[0]),params[1]);
				//params得到的是一个数组，params[0]在这里是"0",params[1]是"第1项"
				Adapter.notifyDataSetChanged();
			return null;	
		}
    }
    private OnItemClickListener lvLis=new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			//点击条目时触发
			//arg2即为点中项的位置
			setTitle(String.valueOf(arr.get(arg2)));
 
		}
 
    };
 
}
```

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

# Listview动态加载数据

[收藏](home.php?mod=spacecp&ac=favorite&type=article&id=14291&handlekey=favoritearticlehk_14291) [分享](home.php?mod=spacecp&ac=share&type=article&id=14291&handlekey=sharearticlehk_14291) 2011-3-22 11:30| 发布者: [annmax](http://space.189works.com/space-uid-10023030.html)| 查看数: 456| 评论数: 0

&lt;!--\[diy=diysummarytop]--&gt;&lt;!--\[/diy]--&gt;

**摘要**: 最近在研究网络数据加载的问题，比如我有几百，甚至上千条数据，这些数据如果一次性全部加载到arraylist，然后再加载到Listview中。我们必然会去单独开线程来做，这样造成的结果就是会出现等待时间很长，用户体验非 ...

&lt;!--\[diy=diysummarybottom]--&gt;&lt;!--\[/diy]--&gt;

&lt;!--\[diy=diycontenttop]--&gt;&lt;!--\[/diy]--&gt;

   最近在研究网络数据加载的问题，比如我有几百，甚至上千条数据，这些数据如果一次性全部加载到arraylist，然后再加载到Listview中。我们必然会去单独开线程来做，这样造成的结果就是会出现等待时间很长，用户体验非常不好。我的想法是动态加载数据，第一次加载十条，然后往下面滑动的时候再追加十条，再往下面滑动的时候再去追加，这样大大减少了用户等待的时间，同时给处理数据留下了时间。网上看到了这样一个例子，挺好的，我改动了一下，达到了我想要的结果。  
import android.app.Activity;  
import android.os.Bundle;  
import android.os.Handler;  
import android.os.Message;  
import android.view.Gravity;  
import android.view.View;  
import android.view.ViewGroup;  
import android.widget.AbsListView;  
import android.widget.BaseAdapter;  
import android.widget.LinearLayout;  
import android.widget.ListView;  
import android.widget.ProgressBar;  
import android.widget.TextView;  
import android.widget.Toast;  
import android.widget.AbsListView.OnScrollListener;  
import android.widget.LinearLayout.LayoutParams;  
public class ListViewForLoading extends Activity implements OnScrollListener {  
    private listViewAdapter adapter = new listViewAdapter();  
    ListView listView;  
    LinearLayout loadingLayout;  
    private Thread mThread;  
    /\**  
     * 设置布局显示属性  
     \*/  
    private LayoutParams mLayoutParams = new LinearLayout.LayoutParams(  
            LinearLayout.LayoutParams.WRAP\_CONTENT,  
            LinearLayout.LayoutParams.WRAP\_CONTENT);  
    /\**  
     * 设置布局显示目标最大化属性  
     \*/  
    private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(  
            LinearLayout.LayoutParams.FILL\_PARENT,  
            LinearLayout.LayoutParams.FILL\_PARENT);  
    private ProgressBar progressBar;  
    /\** Called when the activity is first created. \*/  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        init();  
    }  
    private void init() {  
        // TODO Auto-generated method stub  
        // 线性布局  
        LinearLayout layout = new LinearLayout(this);  
        // 设置布局 水平方向  
        layout.setOrientation(LinearLayout.HORIZONTAL);  
        // 进度条  
        progressBar = new ProgressBar(this);  
        // 进度条显示位置  
        progressBar.setPadding(0, 0, 15, 0);  
        // 把进度条加入到layout中  
        layout.addView(progressBar, mLayoutParams);  
        // 文本内容  
        TextView textView = new TextView(this);  
        textView.setText("加载中...");  
        textView.setGravity(Gravity.CENTER\_VERTICAL);  
        // 把文本加入到layout中  
        layout.addView(textView, FFlayoutParams);  
        // 设置layout的重力方向，即对齐方式是  
        layout.setGravity(Gravity.CENTER);  
        // 设置ListView的页脚layout  
        loadingLayout = new LinearLayout(this);  
        loadingLayout.addView(layout, mLayoutParams);  
        loadingLayout.setGravity(Gravity.CENTER);  
        // 得到一个ListView用来显示条目  
        listView = (ListView) findViewById(R.id.tv);  
        // 添加到脚页显示  
        listView.addFooterView(loadingLayout);  
        // 给ListView添加适配器  
        listView.setAdapter(adapter);  
        // 给ListView注册滚动监听  
        listView.setOnScrollListener(this);  
    }  
    /\**  
     * 要用用于生成显示数据  
     *  
     * @author huangbq  
     *  
     \*/  
    class listViewAdapter extends BaseAdapter {  
        int count = 10;  
        public int getCount() {  
            return count;  
        }  
        public Object getItem(int pos) {  
            return pos;  
        }  
        public long getItemId(int pos) {  
            return pos;  
        }  
        public View getView(int pos, View v, ViewGroup p) {  
            TextView view;  
            if (v == null) {  
                view = new TextView(ListViewForLoading.this);  
            } else {  
                view = (TextView) v;  
            }  
            view.setText("ListItem " + pos);  
            view.setTextSize(20f);  
            view.setGravity(Gravity.CENTER);  
            view.setHeight(60);  
            return view;  
        }  
    }  
    @Override  
    public void onScroll(AbsListView view, int firstVisibleItem,  
            int visibleItemCount, int totalItemCount) {  
        // TODO Auto-generated method stub  
        if(firstVisibleItem+visibleItemCount==totalItemCount)  
        {  
            //开线程去下载网络数据  
            if (mThread == null || !mThread.isAlive()) {  
                mThread = new Thread() {  
                    @Override  
                    public void run() {  
                        try {  
                            //这里放你网络数据请求的方法，我在这里用线程休眠5秒方法来处理  
                            Thread.sleep(5000);  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                        Message message = new Message();  
                        message.what = 1;  
                        handler.sendMessage(message);  
                    }  
                };  
                mThread.start();                 
            }  
        }  
    }  
    @Override  
    public void onScrollStateChanged(AbsListView view, int scrollState) {  
        // TODO Auto-generated method stub         
    }  
    private Handler handler = new Handler() {  
        @Override  
        public void handleMessage(Message msg) {  
            // TODO Auto-generated method stub  
            switch (msg.what) {  
            case 1:  
                if (adapter.count &lt;= 41) {  
                    adapter.count += 10;  
                    int currentPage = adapter.count / 10;  
                    Toast.makeText(getApplicationContext(),"第" + currentPage + "页", Toast.LENGTH\_LONG).show();  
                } else {  
                    listView.removeFooterView(loadingLayout);  
                }  
                //重新刷新Listview的adapter里面数据  
                adapter.notifyDataSetChanged();  
                break;  
            default:  
                break;  
            }  
        }  
    };  
}  
运行结果如下图：

[![](http://www.189works.com/data/attachment/portal/201103/22/11293708un0nieo8eeouee.png)](http://www.189works.com/data/attachment/portal/201103/22/11293708un0nieo8eeouee.png)

[![](http://www.189works.com/data/attachment/portal/201103/22/112940atskzmyko1fy4gyg.png)](http://www.189works.com/data/attachment/portal/201103/22/112940atskzmyko1fy4gyg.png)

[![](http://www.189works.com/data/attachment/portal/201103/22/112943rmzmz5kwmbwahw5s.png)](http://www.189works.com/data/attachment/portal/201103/22/112943rmzmz5kwmbwahw5s.png)