标签:
listview的动态刷新主要是调用adapter的notifyDataSetChanged。
在下面的例子中除了记录正常的刷新外,还记录一种错误的情况(注释掉的),作为备忘。
notifyDataSetChanged除了数据无改变时不起作用,当数据的引用变化时也不起作用。因此在下面那个用数组的例子里,listview不会更新。
package com.example.demo_dlv; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { private ListView lv; /*private String[] strs = new String[] { "first", "second", "third", "fourth", "fifth" };*/ private List<String> list; private static int i = 0; private ArrayAdapter<String> adapter; private Handler handler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case 1: /*List<String> list = new ArrayList<String>(); for (int i=0; i<strs.length; i++) { if(!list.contains(strs[i])) { list.add(strs[i]); } } list.add("new Element" + i++);*/ list.add("item" + i++); System.out.println(list.size()); //strs = (String[]) list.toArray(new String[1]); 引用变了,无法动态刷新 adapter.notifyDataSetChanged(); break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); list = new ArrayList<String>(); list.add("item1"); list.add("item2"); list.add("item3"); list.add("item4"); list.add("item5"); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list); lv.setAdapter(adapter); MyThread mt = new MyThread(); new Thread(mt).start(); } class MyThread implements Runnable{ @Override public void run() { int i = 0; while(i < 3){ try { Thread.sleep(3000); Message message = new Message(); message.what = 1; handler.sendMessage(message); i++; } catch (InterruptedException e) { e.printStackTrace(); } } } } }
标签:
原文地址:http://www.cnblogs.com/Fredric-2013/p/4883896.html