android 中遇到 imageView getWidth 始終為0 時 ,設定 setImageBitmap 的方法

來源:互聯網
上載者:User

標籤: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方法 了。在這裡完成我們需要的功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.