標籤:android style blog color 使用 strong
先說說我的遇到的問題:
1. 我在activity裡寫一個 fragment
2.這個fragment裡有個 imageView ,用於顯示圖片。
我使用 asyncTask獲得圖片,並準備在這個imageView 中顯示該圖片的縮圖,我準備使用 ThumbnailUtils.extractThumbnail 方法產生縮圖。
我們先看看ThumbnailUtils.extractThumbnail(source, width, height); 這個方法的參數
source 源檔案(Bitmap類型)
width 壓縮成的寬度
height 壓縮成的高度
這裡需要一個寬度和高度的參數。。要想再imageView裡填滿圖片的話,這裡就應該傳入imageView的寬度和高度。
然而問題來了:在這裡,使用imageView.getWidth方法獲得寬度始終為0
經過一番搜尋,終於找到解決方案,如下:
private void showImage(final File resultFileArg) { if (resultFileArg != null && resultFileArg.exists()) { // 添加下載圖片至 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); } }); } }
使用步驟:
1.先獲得imageView 的 一個ViewTreeObserver 對象。方法: imageView1.getViewTreeObserver()
2.為這個ViewTreeObserver 對象添加監聽器(比如叫OnGlobalLayoutListener),方法:vto2.addOnGlobalLayoutListener
3.完成這個 OnGlobalLayoutListener的具體實現,在這個實現方法裡就可以調用 imageView.getWidth方法 了。在這裡完成我們需要的功能。