ListView複用導致圖片錯亂及閃爍問題
阿新 • • 發佈:2019-02-11
關於ViewHolder複用,我就不說明了,關鍵是複用導致出現的問題
網路的好壞,我們請求的圖片並不是很穩定,那麼我們假設一屏可以顯示6條資料,利用複用,我們的第7條資料view就是我們的第1條資料view,隨之手勢不斷的滑動,複用的問題,就出現,特別是上網請求網路圖片, 我們在顯示第7條資料時,圖片還是第1個數據圖片,因為第7條很可以沒有載入完成,導致view複用,圖片錯亂,那麼如何解決呢
- 給每個 ImageView設定tag ,tag 的內容就是唯一的url
- 非同步載入類中輸入url
- 在非同步載入類,完成後,對比ImageView的tag與url是否一致
- 一致就設定圖片,不一致,就不設定,同時setImageBitmap(null)來解決閃爍問題
public class Myadapter extends BaseAdapter {
private List<Info.DataBean> list;
public Myadapter(List<Info.DataBean> list) {
this.list = list;
}
@Override
public int getCount() {
return list == null ? 0 : list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Info.DataBean bean = list.get(position);
MyViewHolder viewHolder = null ;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
viewHolder = new MyViewHolder();
viewHolder.iv = (ImageView) convertView.findViewById(R.id.iv);
viewHolder.cb = (CheckBox) convertView.findViewById(R.id.cb);
viewHolder.title = (TextView) convertView.findViewById(R.id.item_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (MyViewHolder) convertView.getTag();
}
viewHolder.title.setText(bean.getTitle());
viewHolder.iv.setTag(bean.getImgs().get(0)); //內容為url的tag
viewHolder.iv.setImageBitmap(null); //解決閃爍
new MyNet(viewHolder.iv).execute(bean.getImgs().get(0)); //載入類中url為圖片的url
return convertView;
}
static class MyViewHolder {
private ImageView iv;
private TextView title;
private CheckBox cb;
}
class MyNet extends AsyncTask<String, Void, byte[]> {
private ImageView iv;
private String path;
public MyNet(ImageView imageView) {
this.iv = imageView;
}
@Override
protected byte[] doInBackground(String... params) {
try {
URL url = new URL(params[0]);
path = params[0];
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK && !isCancelled()) {
InputStream inputStream = con.getInputStream();
int len;
byte[] buff = new byte[1024 * 4];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
while ((len = inputStream.read(buff)) != -1) {
bao.write(buff, 0, len);
}
inputStream.close();
return bao.toByteArray();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
};
@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
if (bytes != null && iv.getTag().equals(path)) { //載入類中,回來直接判斷是不是最新的tag 也 就是最新滑動的item
iv.setImageBitmap(BitmapFactory.decodeByteArray(bytes,0,bytes.length));
}
}
}
}