ListView解决网络图片闪图问题
闪图问题根本原因是网络图片还没缓存下来就呈现,出现异步错误。
解决的方法也就是让网络图片先缓存下来,然后再呈现出来
一种方法是导入一个SmartImageView类库,然后调用setImageUrl(url)方法
holder.mIvHead.setImageUrl(user.headImg);
url参数是一个字符串路径
具体代码
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder = null;
if (view == null) {
view = View.inflate(context, R.layout.msg_list_item, null);
holder = new ViewHolder();
holder.mIvHead = (SmartImageView) view.findViewById(R.id.ivHead);
holder.mTvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
User user = userList.get(position);
holder.mTvName.setText(user.name);
holder.mIvHead.setImageUrl(user.headImg);
return view;
}
另一种方法是添加一个Picasso jar包
加上一句代码
Picasso.with(context).load(user.headImg).into(holder.mIvHead);
具体代码
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder = null;
if (view == null) {
view = View.inflate(context, R.layout.msg_list_item, null);
holder = new ViewHolder();
holder.mIvHead = (ImageView) view.findViewById(R.id.ivHead);
holder.mTvName = (TextView) view.findViewById(R.id.tvName);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// TextView mTvName = (TextView) view.findViewById(R.id.tvName);
// mIvHead = (ImageView) view.findViewById(R.id.ivHead);
User user = userList.get(position);
holder.mTvName.setText(user.name);
Picasso.with(context).load(user.headImg).into(holder.mIvHead);
return view;
}
以上两种问题都可以解决闪图问题,或者自己写,先把图片缓存下来,然后再做呈现工作。
第一次获得的网络请求的图片写到内存中去
public static Bitmap getImageHttpClientGet(String path) throws Exception
{
// 缓存
// ? 本地有没有? /aaaa.jpg
String localPath = CommonApplication.context.getCacheDir().getPath()
+ "/" + UUID.nameUUIDFromBytes(path.getBytes()).toString();
File file = new File(localPath);
if (file.exists())
{
FileInputStream fileInputStream = new FileInputStream(file);
return BitmapFactory.decodeStream(fileInputStream);
} else
{
// 抽象类
HttpClient client = new DefaultHttpClient();
// 参数编码
// path = URLEncoder.encode(path);
// 创建请求 http
HttpGet httpGet = new HttpGet(path);
HttpResponse response = client.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200)
{
HttpEntity entity = response.getEntity();
InputStream in = entity.getContent();
byte[] bytes = StreamUtil.getBytesByInputStream(in, localPath);
Bitmap decodeByteArray = BitmapFactory.decodeByteArray(bytes,
0, bytes.length);
return decodeByteArray;
}
}
return null;
}