Android使用OnPreDrawListener获取imageview宽度和高度

时间:2014-01-01 05:59:49

标签: android

我使用OnPreDrawListener来获取imageview宽度并且Hieght它正确返回但是我不能在该方法之外使用

在OnCreate中

    @Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawingarea);
    img=(ImageView)findViewById(R.id.imageView1);

    ViewTreeObserver vto = img.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {     
        public boolean onPreDraw(){
            // at this point, true width and height are already determined
          int width = img.getMeasuredWidth();
          int height = img.getMeasuredHeight();
          System.out.println(width);// it return value correctly
          System.out.println(height);//it return value correctly
            img.getViewTreeObserver().removeOnPreDrawListener(this);
            return false;
        }
    });
     System.out.println(width);// it return 0
     System.out.println(height);//it return 0
    }

如何获取值outsite addOnPreDrawListener请帮助

1 个答案:

答案 0 :(得分:5)

全局声明你的变量......

private int width;
private int height;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawingarea);
    img = (ImageView) findViewById(R.id.imageView1);

    ViewTreeObserver vto = img.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            // at this point, true width and height are already determined
            width = img.getMeasuredWidth();
            height = img.getMeasuredHeight();
            System.out.println(width);// it return value correctly
            System.out.println(height);// it return value correctly
            img.getViewTreeObserver().removeOnPreDrawListener(this);
            return false;
        }
    });
    System.out.println(width);// it return 0
    System.out.println(height);// it return 0
}

并且您在onCreate()中获得了正确的值,我的意思是onCreate()中的宽度和高度将为零,因为您的ImageView的绘图尚未执行...您可以检查这些值onWindowFocusChanged()。并且在绘制宽度和高度值时将调用您的onPreDrawListener回调,因为ImageView在绘制之前已经测量并进行了布局...