Reputation: 517
I have an ImageView with its visibility set as GONE. I am trying to set a Bitmap Resource onto it and make it appear.
I realize the dimensions of the ImageView (which I need to subsample my bitmap appropriately) is zero when it's visibility is still GONE, so I set this line of code just before my BitmapAsyncTask runs.
ImageView postImageView= (ImageView) getActivity().findViewById(R.id.post_image);
// Set it as visible to take up necessary space for bitmap computation
postImageView.setVisibility(View.INVISIBLE);
The dimensions still return zero and upon further testing, the ImageView takes some time before it's visibility is set to INVISIBLE again. My fix for now is a while loop inside the AsyncTask to wait until the dimensions are available, but I would like to find out whether there is a better way to do this?
My current code for the AsyncTask:
@Override
protected Bitmap doInBackground(Void... voids) {
Log.i(TAG,"BitmapWorkerTask initialized.");
while(mImageView.getWidth() ==0){
// Wait for the ImageView to be ready
Log.i(TAG,"asd");
}
int reqWidth = mImageView.getWidth()==0?1920:mImageView.getWidth();
int reqHeight = mImageView.getHeight()==0?1080:mImageView.getHeight();
Log.i(TAG, "Dimensions (required): "+reqWidth+" X "+ reqHeight);
//Decode and scale image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, options);
Log.i(TAG, "Dimensions (source): "+options.outWidth+" X "+ options.outHeight);
options.inSampleSize = calculateInSampleSize(options,reqWidth, reqHeight);
options.inJustDecodeBounds = false;
Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath,options);
Log.i(TAG,"Dimensions (Bitmap): "+ imageBitmap.getWidth()+" X "+ imageBitmap.getHeight());
return imageBitmap;
}
Upvotes: 2
Views: 686
Reputation: 44118
Try adding a layout listener, to wait for the layout to be measured:
final ImageView postImageView = (ImageView) getActivity().findViewById(R.id.post_image);
postImageView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View view, int i, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
postImageView.removeOnLayoutChangeListener(this);
Log.e(TAG, "W:" + postImageView.getWidth() + " H:"+postImageView.getHeight());
}
});
postImageView.setVisibility(View.INVISIBLE);
Upvotes: 3