2014-10-27 63 views
2

我有一个ImageView及其可见性设置为GONE。我正试图设置一个位图资源并使其显示。设置查看可见性以隐形并获取尺寸

我实现的ImageView的尺寸(我需要适当地进行二次采样我的位图)为零时,它的能见度仍然GONE,所以我设置这行代码我BitmapAsyncTask运行之前。

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); 

尺寸还是回到零,并在进一步的测试中,ImageView的需要一些时间之前的知名度再次设置为不可见。我现在修复的是AsyncTask内部的一个while循环,等待这些维度可用,但是我想知道是否有更好的方法来做到这一点?

我对当前的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; 
} 

回答

3

尝试添加布局监听,等待布局来衡量:

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); 
+0

谢谢!我把我的AsyncTask放在OnLayoutChange里面,它完美的工作:) – daidaidai 2014-10-27 11:34:44

+0

@daidaidai不客气:) – Simas 2014-10-27 11:38:07