Let’s talk about my problems:

1. I write a fragment in the activity

2. There is an imageView in this Fragment, which is used to display images.

I use asyncTask to obtain images, and ready to show the image thumbnails in this imageView, ThumbnailUtils. I plan to use generated thumbnail extractThumbnail method.

 

Let’s look at ThumbnailUtils. ExtractThumbnail (source, width, height); Arguments to this method

Source Source file (Bitmap type) Width Compressed width height compressed height

Here we need a width and height parameter. In order to fill the imageView with images, you need to pass in the width and height of the imageView.

Here’s the problem: using the imageView.getwidth method to get the width always 0

 

After some searching, I finally found a solution as follows:

private void showImage(final File resultFileArg) { if (resultFileArg ! = null && resultFileArg. The exists ()) {/ / download images to add imageView ViewTreeObserver vto2 = imageView1. GetViewTreeObserver (); vto2.addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < 16) { imageView1.getViewTreeObserver().removeGlobalOnLayoutListener(this); } else { imageView1.getViewTreeObserver().removeOnGlobalLayoutListener(this); } Bitmap bm = BitmapFactory.decodeFile(resultFileArg.getPath()); Bitmap thumbnailImg = ThumbnailUtils.extractThumbnail(bm, imageView1.getMeasuredWidth(), imageView1.getMeasuredHeight()); bm.recycle(); imageView1.setImageBitmap(thumbnailImg); // imageView1.setImageBitmap(bm); }}); }}Copy the code

 

Use steps:

1. Get a ViewTreeObserver object from imageView. Methods: imageView1. GetViewTreeObserver ()

2. Add the listener objects for the ViewTreeObserver (such as call OnGlobalLayoutListener), methods: vto2. AddOnGlobalLayoutListener

3. Complete the OnGlobalLayoutListener implementation, in this implementation method can call imageView.getWidth method. This is where we do what we need to do.