繼上一篇放大招了!基於Bmob的Android即時通信應用源碼 (一) 用到的ViewHolderjava
viewHolder 就不解釋了,懂的人都懂!!!不懂就問度娘!!!ide
廢話很少說,進入正題!!!函數
你們一般怎麼寫ViewHolder呢?優化
[mw_shl_code=java,true] ViewHolder holder = null;
if(convertView == null){
convertView = mInflater.inflate(R.layout.xxx null);
holder = new ViewHolder();
holder.tvXXX = (TextView)findViewById(R.id.xxx);
//...一連串的findViewById
}
else{
holder = (ViewHolder) convertView.getTag();
}
private static class ViewHolder{
TextView tvXXX;
//不少view的定義
}[/mw_shl_code]網站
這麼寫一次還行,但問題是總有不少不少的ViewAdapter要這麼寫,每次都repeat,repeat,repeat 累啊。 因此,有這麼一種簡潔的寫法分享給你們,先聲明,從國外網站上看的,不是本身原創的,但確實很喜歡這個簡潔的設計。spa
很激動有木有!!!.net
ViewHolder這麼寫(只提供一個靜態方法,其實能夠加一個私有構造函數防止外部實例化),代碼很簡單,看過就明白了
[mw_shl_code=java,true]public class ViewHolder {
// I added a generic return type to reduce the casting noise in client code
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
}[/mw_shl_code]
在getView裏這樣
[mw_shl_code=java,true]@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.banana_phone, parent, false);
}
ImageView bananaView = ViewHolder.get(convertView, R.id.banana);
TextView phoneView = ViewHolder.get(convertView, R.id.phone);
BananaPhone bananaPhone = getItem(position);
phoneView.setText(bananaPhone.getPhone());
bananaView.setImageResource(bananaPhone.getBanana());
return convertView;
}[/mw_shl_code]
哈哈,完成了,果斷把這個ViewHolder類加入本身的utils,一勞永逸了之後~
值得注意的是SparseArray這個知識點,優化過的存儲integer和object鍵值對的hashmap,網上資料不少這裏就不廢話了~設計
Get到這個技能的朋友就多多回復頂貼哦!!!code