各位,我在使用listview时遇到了一个问题。当滚动时,它运行得非常缓慢,有人能帮我吗?我的listview是自定义布局,每一行都有3个textview和1个imageview,并且所有内容都从网络获取。我使用了自定义适配器和视图持有者。
下面是我如何使用适配器的代码:
public class MessageList extends ListActivity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.listarticle);
loadFeed(link);
setListAdapter(new IconAdapter(this));
}
/* This method load xml file and parse it into message object*/
private void loadFeed(String link){
try{
BaseFeedParser parser = new BaseFeedParser(link);
messages = parser.parse();
titles = new ArrayList<String>(messages.size());
image = new ArrayList<String>(messages.size());
date_post = new ArrayList<String>(messages.size());
descs = new ArrayList<String>(messages.size());
for (Message msg : messages){
titles.add(msg.getTitle());
image.add(msg.getImageLink().toString());
date_post.add(msg.getDate());
descs.add(msg.getDescription());
}
} catch (Throwable t){
Log.e("AndroidNews",t.getMessage(),t);
}
}
/*this is my custom baseadapter */
class IconAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public IconAdapter(Context cxt){
mInflater = LayoutInflater.from(cxt);
}
public class ViewHolder{
private TextView title;
private TextView date;
private TextView desc;
private ImageView thumb;
}
public View getView(int positiion, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView==null){
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.title);
holder.date = (TextView) convertView.findViewById(R.id.date);
holder.desc = (TextView) convertView.findViewById(R.id.deskripsi);
holder.thumb = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(titles.get(positiion));
holder.date.setText(date_post.get(positiion));
holder.desc.setText(descs.get(positiion).substring(0, 55)+"...");
Drawable draw = LoadImageFromWebOperation(image.get(positiion));
holder.thumb.setImageDrawable(draw);
return convertView;
}
/* this method take image from url that retrieve from xml*/
public Drawable LoadImageFromWebOperation(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e){
Log.d("image", url, e);
return null;
}
}
@Override
public int getCount() {
return messages.size();
}
@Override
public Object getItem(int position) {
return messages.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
}
getView
方法中不要再次加载它们...这样会加快速度。 - st0le