我从android开发者网站修改了以下类,将图像加载到imageview
。输入了onPostExecute
方法,但我的imageview
未正确刷新。我尝试过使用imageView.refreshDrawableState
,requestFocus
,requestLayout
,但一切都不起作用。
首先,imageview
会显示一些随机颜色或显示任何内容。当我尝试下拉通知栏时,imageview
仅正确显示。我很确定图像已加载,因为内存保持不变但只是没有正确显示/刷新。
我在async task
方法中调用public void onWindowFocusChanged()
。
任何人都可以指出我做错了什么吗?
ImageView imageView; //set in onCreate method
private class ImageViewAsyncTask extends AsyncTask<Integer, Void, Bitmap>
{
private final WeakReference<ImageView> imageViewWeakReference;
Activity activity;
public ImageViewAsyncTask(Activity activity)
{
this.activity = activity;
this.imageViewWeakReference = new WeakReference<>(imageView);
}
public int calculateInSampleSize(Options options)
{
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
int reqWidth = imageView.getWidth();
int reqHeight = imageView.getHeight();
if (width > reqWidth || height > reqHeight)
{
final int halfWidth = width / 2;
final int halfHeight = height / 2;
while ((halfWidth / inSampleSize) > reqWidth && (halfHeight / inSampleSize) > reqHeight)
{
inSampleSize *= 2;
}
}
return inSampleSize;
}
public Bitmap decodeSampledBitmapFromResource(Activity activity)
{
byte[] decodedImage = Base64.decode(activity.getResources().getString(R.string.cat), 0);
final Options options = new Options();
options.inJustDecodeBounds = true;
decodeByteArray(decodedImage, 0, decodedImage.length, options);
options.inSampleSize = calculateInSampleSize(options);
options.inJustDecodeBounds = false;
return decodeByteArray(decodedImage, 0, decodedImage.length, options);
}
@Override
protected Bitmap doInBackground(Integer... params)
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
return decodeSampledBitmapFromResource(activity);
}
@Override
protected void onPostExecute(Bitmap bitmap)
{
if (imageViewWeakReference != null && bitmap != null)
{
final ImageView imageView = imageViewWeakReference.get();
if (imageView != null)
{
imageView.setImageBitmap(bitmap);
}
}
}