面试中经常问到listView优化的问题,个人回答主要如下
1、View重用 使用setTag把view缓存起来
2、适配器在主线程修改
3、在主线程提交适配器的变化,并调用notifyDataSetChanged()方法
4、可以在任何地方获取数据,但应该在另外一个地方请求数据,数据多次请求分次显示
简单实例:
package com.android.listviewtest; import java.util.LinkedHashMap; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { //定义view缓存对象 static class HolderView { TextView showName; TextView showInfo; } //一次装载 多次显示 private Map<String, String> maps; // 显示的页数 private int page = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); maps=new LinkedHashMap<String, String>(); for (int i = 0; i < 100; i++) { maps.put("熊"+i, "程序员"+i+"号"); } Button btshow = (Button) findViewById(R.id.bt_show); ListView showlist = (ListView) findViewById(R.id.listshow); final ShowName showName = new ShowName(); showlist.setAdapter(showName); btshow.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (page< 100 / 5) { page++; showName.notifyDataSetChanged(); }else{ Toast.makeText(MainActivity.this, "没有多余的数据了", Toast.LENGTH_LONG).show(); } } }); } class ShowName extends BaseAdapter { // 每次加载5条数据 @Override public int getCount() { return page * 5; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { HolderView holderView; //判断每一个item中的view是否已经存在 if (convertView == null) { //加载view convertView = LayoutInflater.from(MainActivity.this).inflate( R.layout.show_name, null); holderView = new HolderView(); holderView.showName = (TextView) convertView .findViewById(R.id.txt1); holderView.showInfo = (TextView) convertView .findViewById(R.id.txt2); //添加一个额外的数据 convertView.setTag(holderView); } else { holderView = (HolderView) convertView.getTag(); } String name=((maps.keySet().toArray())[position]).toString(); String info=maps.get(name); holderView.showName.setText(name); holderView.showInfo.setText(info); return convertView; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }