我正在开发社交应用程序,马上就要完成了,但我被一个问题卡住了,那就是图像闪烁。当屏幕上大约有9到10个图像时,如果我滚动页面,图像就会闪烁。
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.view_grid_explore, null);
holder = new ViewHolder();
holder.img = (ImageView) convertView.findViewById(R.id.img_grid_album);
} else {
holder = (ViewHolder) convertView.getTag();
}
ImageLoader.getInstance().displayImage(
Static_Urls.explore_pic + data.get(position).talk_pic,
holder.img);
convertView.setTag(holder);
notifyDataSetChanged();
return convertView;
}
发布于 2016-01-23 13:31:47
notifyDataSetChanged();
.这是因为一旦UIL(通用图像加载器)将图像下载到设备中,它就会将图像缓存到内存和设备中。
通过使用以下代码:
ImageLoader.getInstance().displayImage(Static_Urls.explore_pic +data.get(position).talk_pic,
holder.img);
每次调用getView()
时,UIL都会尝试从网络中获取图像,但在它释放时,该图像已经被缓存,因此它首先在发出网络请求后显示该图像。
因此,为了消除这种闪烁,请使用以下代码:
ImageLoader imageLoader = ImageLoader.getInstance();
File file = imageLoader.getDiskCache().get(Static_Urls.explore_pic +data.get(position).talk_pic);
if (file==null) {
//Load image from network
imageLoader.displayImage(Static_Urls.explore_pic +data.get(position).talk_pic,
holder.img);
}
else {
//Load image from cache
holder.img.setImageURI(Uri.parse(file.getAbsolutePath()));
}
此代码将首先检查图像是否已缓存,然后相应地从网络或缓存中获取图像。
发布于 2016-01-25 12:33:51
notifyDataSetChanged()
行在那里是多余的。使用适配器时,请始终记住(在适配器扩展BaseAdapter的情况下) getView()
方法负责扩展列表项的布局,如果您处理它,还负责更新UI (通常是这样做的)
调用notifyDataSetChanged()
将导致getView()
立即再次被调用,这就是您看到闪烁的原因。
只有当您想要更新适配器内容时,才应该调用notifyDataSetChanged()
。例如,当您在适配器中构建"refresh()“方法时,如下所示:
public void refresh(List<Object> list) {
data.clear();// Assuming data is a List<> object or an implementation of it like ArrayList();
data.addAll(list);
notifyDataSetChanged(); // This will let the adapter know that something changed in the adapter and this change should be reflected on the UI too, thus the getView() method will be called implicitly.
}
https://stackoverflow.com/questions/34963834
复制相似问题