Android 如何获取ImageView的高度和宽度?
我正在尝试获取ImageView机器人的高度和宽度,它返回0Android 如何获取ImageView的高度和宽度?,android,android-imageview,Android,Android Imageview,我正在尝试获取ImageView机器人的高度和宽度,它返回0 public class FullScreenImage extends FragmentActivity { ImageView full_view; int width; int height; @Override protected void onCreate(Bundle arg0) { super.onCreate(arg0); setContentV
public class FullScreenImage extends FragmentActivity {
ImageView full_view;
int width;
int height;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.full_screen);
full_view = (ImageView)findViewById(R.id.full_view);
Bundle bundle=getIntent().getExtras();
byte[] image= bundle.getByteArray("image");
width = full_view.getWidth();
height = full_view.getHeight();
Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);
full_view.setImageBitmap(resized);
}
}
请帮助我,如何从ImageView中找到它?Android新开发人员的一个常见错误是在其构造函数中使用视图的宽度和高度。当调用视图的构造函数时,Android还不知道视图有多大,所以大小设置为零。实际尺寸是在布局阶段计算的,布局阶段发生在施工之后,但在绘制任何内容之前。您可以在已知值时使用
onSizeChanged()
方法来通知这些值,也可以稍后使用getWidth()
和getHeight()
方法,例如在onDraw()
方法中。如果您第一次获得高度和宽度,则此时没有可用图像,因此结果为0
请使用此代码:
setContentView(R.layout.full_screen);
full_view = (ImageView)findViewById(R.id.full_view);
Bundle bundle=getIntent().getExtras();
byte[] image= bundle.getByteArray("image");
Bitmap theImage = BitmapFactory.decodeByteArray(image, 0, image.length);
Bitmap resized = Bitmap.createScaledBitmap(theImage,width , height, true);
full_view.setImageBitmap(resized);
width = full_view.getWidth();
height = full_view.getHeight();
看
除了Farhan已经提到的内容,您还可以看看
http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html
int finalHeight, finalWidth;
final ImageView iv = (ImageView)findViewById(R.id.scaled_image);
final TextView tv = (TextView)findViewById(R.id.size_label);
ViewTreeObserver vto = iv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
finalHeight = iv.getMeasuredHeight();
finalWidth = iv.getMeasuredWidth();
tv.setText("Height: " + finalHeight + " Width: " + finalWidth);
return true;
}
});