1、 複用行佈局(用已經完全消失的佈局對象去替代即將出現的那個佈局對象)
在自定義MyAdapter(繼承BaseAdapter)適配器時,需重寫getVIew(int position, View convertView, ViewGroup parent)方法,其中的converView方法會保存那個已經完全消失的佈局對象,因此我們用convertView來替代即將要創建的inflate
(判斷convertView爲空時創建佈局文件,不爲空時直接用convertView來替代)
實現代碼:
View inflate = null;
if(convertView==null){
//得到佈局轉換器
LayoutInflater layoutInflater= getLayoutInflater();
//把佈局xml文件轉換成佈局對象
inflate = layoutInflater.inflate(R.layout.item,null);
}else{
//用已經完全消失的佈局對象去替代即將出現的佈局對象
inflate = convertView;
}
2、去減少控件的查找次數
2.1 單控件——將TextView位置上調
實現代碼:
Viewinflate = null;
TextViewtextView = null;
if(convertView==null){
LayoutInflaterlayoutInflater = getLayoutInflater();
//把佈局xml文件轉換成佈局對象
inflate= layoutInflater.inflate(R.layout.item, null);
textView= (TextView) inflate.findViewById(R.id.textView1);
//把ViewHolder對象放到inflate包裏面
inflate.setTag(textView);
}else{
//用已經完全消失的佈局對象去替代即將出現的佈局對象
inflate= convertView;
//把對象從inflate的口袋中
textView= inflate.getTag();
}
2.2 多控件——使用ViewHolder:創建對象ViewHolder,將TextView封裝到新ViewHolder中(放入的是多控件)
實現代碼:
================================================
classViewHolder{
TextViewtextView;
TextViewtextView2;
}
================================================
Viewinflate = null;
ViewHolderholder = null;
//convertView用來保存那個已經完全消失的佈局對象
if(convertView==null){
holder= new ViewHolder();
//得到佈局轉換器
LayoutInflaterlayoutInflater = getLayoutInflater();
//把佈局xml文件轉換成佈局對象
inflate= layoutInflater.inflate(R.layout.item, null);
holder.textView= (TextView) inflate.findViewById(R.id.textView1);
holder.textView2= (TextView) inflate.findViewById(R.id.textView2);
//把ViewHolder對象放到inflate包裏面
inflate.setTag(holder);
}else{
//用已經完全消失的佈局對象去替代即將出現的佈局對象
inflate= convertView;
//把對象從inflate的口袋中
holder= (ViewHolder) inflate.getTag();
}
3、代碼優化
1、創建一個類,類的屬性就是我們所需的數據類型
2、創建一個容器
3、把所需的數據都放到容器中
4、根據position從容器中取出該行所對應的那個對象
5、設置控件內容