zoukankan      html  css  js  c++  java
  • android 中遇到 imageView getWidth 始终为0 时 ,设置 setImageBitmap 的方法

    先说说我的遇到的问题:

    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方法 了。在这里完成我们需要的功能。

  • 相关阅读:
    crossvcl使用
    CSS垂直居中的方法
    IIS7 启用GZip压缩
    javascript arguments解释,实现可变长参数。
    DataTable转List<dynamic>
    Bootstrap表单
    Func<T>、Action<T> 的区别于说明
    jQuery.fn.extend() 与 jQuery.extend()
    javascript this关键字指向详解
    javascript call与apply关键字的作用
  • 原文地址:https://www.cnblogs.com/vir56k/p/3853698.html
Copyright © 2011-2022 走看看