更新ListView的几种方法

1、直接用notifyDataSetChanged()的方法

2、用Message的sendEmptyMessage(0)方法

3、用Message的实例化传入callback

4、单例message

activity_main.xml



    

    

        

            
package com.example.updatelistview;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class MainActivity extends Activity implements OnClickListener {
	private Button btn1, btn2,btn3,btn4;
	private ArrayAdapter myAdapter;
	private List stringList;
	private ListView lv;
	private Handler myHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		stringList = new ArrayList();
		stringList.add("1");
		stringList.add("2");
		stringList.add("3");
		stringList.add("4");
		stringList.add("5");
		myAdapter = new ArrayAdapter(MainActivity.this,
				android.R.layout.simple_list_item_1, stringList);
		lv = (ListView) findViewById(R.id.lv);
		lv.setAdapter(myAdapter);
		btn1 = (Button) findViewById(R.id.btn1);
		btn2 = (Button) findViewById(R.id.btn2);
		btn3 = (Button) findViewById(R.id.btn3);
		btn4=(Button) findViewById(R.id.btn4);
		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);
		btn4.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn1:
			stringList.remove(0);
			myAdapter.notifyDataSetChanged();
			break;
		case R.id.btn2:
			stringList.remove(0);
			myHandler=new MyHandler();
			myHandler.sendEmptyMessage(0);
			break;
		case R.id.btn3:
			stringList.remove(0);
			myHandler=new Handler(callback);
			myHandler.sendEmptyMessage(0);
			break;
		case R.id.btn4:
			stringList.remove(0);
			//单例message,不会消耗内存
			String str="lhm";
			Message m=Message.obtain();
			m.obj=str;
			m.what=0;
			myHandler=new MyHandler();
			myHandler.sendMessage(m);
			break;
		default:
			break;
		}
	}

	public class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				myAdapter = new ArrayAdapter(MainActivity.this,
						android.R.layout.simple_list_item_1, stringList);
				lv.setAdapter(myAdapter);
				break;

			default:
				break;
			}
		}
	}
	
				
	Callback callback=new Callback() {
		
		@Override
		public boolean handleMessage(Message msg) {
			myAdapter = new ArrayAdapter(MainActivity.this,
					android.R.layout.simple_list_item_1, stringList);
			lv.setAdapter(myAdapter);
			return false;
		}
	};
}



 

你可能感兴趣的:(Android功能)