展会信息港展会大全

高效list adapter
来源:互联网   发布日期:2015-10-02 16:21:10   浏览:2397次  

导读:Android api demo里面有一个编写高效list adapter的demo,里面写了建议的两条高效原则1. 在getView方法中,重复利用 convertView,conve...

Android api demo里面有一个编写高效list adapter的demo,里面写了建议的两条高效原则

1. 在getView方法中,重复利用 convertView,convertView是旧的View,建议先判断是否为空,如果不为空,可以修改其内容来显示新的row。

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

SpeechView sv;

if (convertView == null) {

sv = new SpeechView(mContext, mTitles[position],

mDialogue[position]);

} else {

sv = (SpeechView) convertView;

sv.setTitle(mTitles[position]);

sv.setDialogue(mDialogue[position]);

}

return sv;

}

2. 在getView方法中,利用ViewHolder来保存与convertView相关联的子View,避免调用 findViewById方法,以提高效率

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

// A ViewHolder keeps references to children views to avoid unneccessary calls

// to findViewById() on each row.

ViewHolder holder;

// When convertView is not null, we can reuse it directly, there is no need

// to reinflate it. We only inflate a new View when the convertView supplied

// by ListView is null.

if (convertView == null) {

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

// Creates a ViewHolder and store references to the two children views

// we want to bind data to.

holder = new ViewHolder();

holder.text = (TextView) convertView.findViewById(R.id.text);

holder.icon = (ImageView) convertView.findViewById(R.id.icon);

convertView.setTag(holder);

} else {

// Get the ViewHolder back to get fast access to the TextView

// and the ImageView.

holder = (ViewHolder) convertView.getTag();

}

holder.text.setText(DATA[position]);

holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

return convertView;

}

摘自 达小生

赞助本站

人工智能实验室

相关热词: android开发 教程

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港