我尝试从网络上加载图片(以及一些不在网络上的文字)并将其显示在listview
中。问题是,listview
搞砸了。有些单元格正在快速切换,并且会导致listView
顺序混乱。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null)
itemView = getLayoutInflater().inflate(R.layout.coin_layout, parent, false);
//find the coin to work with.
Coin currentCoin = coins.get(position);
//fill the view
try {
// ImageView coinIcon = (ImageView) itemView.findViewById(R.id.coinIcon);
// coinIcon.setTag(currentCoin.getImageLink());
ViewHolder holder = new ViewHolder();
holder.position = position;
holder.coinIcon = (ImageView) itemView.findViewById(R.id.coinIcon);
holder.coinName = (TextView) itemView.findViewById(R.id.coinName);
holder.coinPrice = (TextView) itemView.findViewById(R.id.coinPrice);
holder.coinPercentage = (TextView) itemView.findViewById(R.id.coinPercentage);
holder.currentCoin = currentCoin;
// holder.coinIcon = (ImageView) itemView.findViewById(R.id.coinIcon);
// Using an AsyncTask to load the slow images in a background thread
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
Log.d("V log", v.currentCoin.getName());
Bitmap bmp = null;
try{
URL ulrn = new URL(v.currentCoin.getImageLink());
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}
catch(Exception e){}
return bmp;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
Log.d("V Posion ", "" + v.position);
// If this item hasn't been recycled already, hide the
// progress and set and show the image
// v.progress.setVisibility(View.GONE);
v.coinIcon.setVisibility(View.VISIBLE);
v.coinIcon.setImageBitmap(result);
v.typeFace = Typeface.createFromAsset(getAssets(), "arial.ttf");
v.coinName.setText(v.currentCoin.getName());
v.coinPrice.setText("" + v.currentCoin.getPrice());
v.coinPercentage.setText(v.currentCoin.getPercentage());
}
}
}.execute(holder);
} catch (NullPointerException e) {
e.printStackTrace();
}
return itemView;
}
答案 0 :(得分:1)
首先,将为每个列表项调用getView()
,并且每次都在分配ViewHolder()
,无论您是否可以重用已创建的ViewHolder()
。此外,我将反对AsyncTask()
内的getView()
而不是你可以使用Android-Universal-Image-Loader库在listView上延迟加载图像,这是非常受欢迎并定期更新。
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
ViewHolder holder = null;
if (itemView == null){
itemView = getLayoutInflater().inflate(R.layout.coin_layout, parent, false);
holder = new ViewHolder();
}
Coin currentCoin = coins.get(position);
try {
holder.position = position;
//... rest of the code
//... rest of the code
return convertView;
}
}
答案 1 :(得分:0)
您不应该在每个getView上创建asyncTasks。您看到的是在重复使用视图或以随机顺序完成加载后图像的结果。查看ThreadPoolExecutor服务。