gpt4 book ai didi

Android 使用 OnPreDrawListener 获取 ImageView 的宽度和高度

转载 作者:太空狗 更新时间:2023-10-29 16:39:14 30 4
gpt4 key购买 nike

我使用 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
}

我怎样才能得到外部addOnPreDrawListener的值(value)请帮助

最佳答案

全局声明变量...

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 在绘制之前已经测量和布局...

关于Android 使用 OnPreDrawListener 获取 ImageView 的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20865995/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com