将视图可见性设置为Invisible并获取尺寸

时间:2014-10-27 11:17:01

标签: android

我有一个ImageView,其可见性设置为 GONE 。我正在尝试将Bitmap资源设置到它上面并使其显示。

我意识到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需要一些时间才能将其可见性再次设置为INVISIBLE。我现在的修复是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;
}

1 个答案:

答案 0 :(得分: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);