ListView的緩存機制

1,ListView的工做原理:緩存

    ListView工做的時候,會針對每一個item,要求Adapter對象返回一個View(getView()方法),也 就是說,Listview在開始繪製的時候,系統首先調用getCount(),根據其返回值獲得ListView的長度,而後根據這個長度,調用 getView()一行一行的繪製ListView的每一項。ide

2,ListView的緩存機制:對象

(1)若是有幾千,幾萬行甚至更多的代碼的時候,其中只有課件的項存在於內存中,其餘的都在Recycler中,Recycle是Android中專門用來處理緩存的組件。內存

(2)ListView先經過getView()方法請求一個View,而後請求其餘可見的View。這時convertView在getView中是空的。get

(3) 當列表第一項滾出屏幕,而且一個新的項從屏幕低端上來時,ListView會再請求一個View,這時,convertView已經不是空值了,它的值是 滾動出屏幕的第一項,以後只須要設定新的數據,而後返回convertView便可,而沒必要從新建立一個View。it

代碼以下:io

public class MainActivity extends ListActivity {class

private MyCustomAdapter mAdapter;原理

@OverrideList

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

mAdapter = new MyCustomAdapter();

for (int i = 0; i < 100; i++) {

mAdapter.addItem("item " + i);

}

setListAdapter(mAdapter);

}

private class MyCustomAdapter extends BaseAdapter {

private ArrayList mData = new ArrayList();

private LayoutInflater mInflater;

public MyCustomAdapter() {

mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public void addItem(final String item) {

mData.add(item);

notifyDataSetChanged();

}

@Override

public int getCount() {

return mData.size();

}

@Override

public String getItem(int position) {

return (String) mData.get(position);

}

@Override

public long getItemId(int position) {

return position;

}

@Override

public View getView(int position, View convertView, ViewGroup parent) {

System.out.println("getView " + position + " " + convertView);

ViewHolder holder = null;

if (convertView == null) {

convertView = mInflater.inflate(R.layout.list_view_item, null);

holder = new ViewHolder();

holder.textView = (TextView) convertView

.findViewById(R.id.title);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

holder.textView.setText((CharSequence) mData.get(position));

return convertView;

}

}

public static class ViewHolder {

public TextView textView;

}

}

相關文章
相關標籤/搜索