英文:
How to get size of an image from xml in android
问题
我正在开发一个使用图像并且拥有约束布局的安卓应用程序。高度和宽度的属性被设置为“wrap-content”,意味着它们并非固定的。在该图像上,我正在使用圆来创建一个图表。为此,我需要知道图像的宽度和高度的确切值。我该如何从XML获取宽度和高度的值到Java中?
英文:
I am developing an android application that uses an image and has a constraint layout. The attributes for height and width are set to "wrap-content" meaning they are not fixed. On that image, I am creating a graph using circles. For that, I should know the exact values of the width and height of the image. How can I get the values of width and height from XML to Java?
答案1
得分: 1
你可以使用 getWidth
和 getHeight
在运行时获取任何视图(在本例中为 constraint layout
)的尺寸。<br />
但要注意,在使用这两个方法之前,你必须确保视图(constraint layout
)已经被创建,否则它会返回 0,这意味着你不能在 onCreate
中调用它们。<br />
因此,正确的做法是等待视图被创建,然后获取其尺寸。
像这样:
创建这个方法
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) {
final OnPreDrawListener preDrawListener = new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
view.getViewTreeObserver().removeOnPreDrawListener(this);
runnable.run();
return true;
}
};
view.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
}
然后在需要获取尺寸时调用它
runJustBeforeBeingDrawn(yourView, new Runnable() {
@Override
public void run() {
// 在这里你可以安全地获取视图尺寸(使用“getWidth”和“getHeight”),并对其进行任何所需操作
}
});
与你的问题相关:<br />
View 的 getWidth() 和 getHeight() 返回 0<br />
在运行时确定 Android 视图的尺寸
英文:
You can use getWidth
and getHeight
to get dimensions of any view (in this case constraint layout
) at runtime.<br />
But be carful, before using this two methods you have to make sure that the view (constraint layout
) is already created, otherwise it gonna return 0, witch means you can't call them in onCreate
.<br />
So the correct way to do it is to wait for the view to be created then get its size.
Like this :
create this method
public static void runJustBeforeBeingDrawn(final View view, final Runnable runnable) {
final OnPreDrawListener preDrawListener = new OnPreDrawListener() {
@Override
public boolean onPreDraw() {
view.getViewTreeObserver().removeOnPreDrawListener(this);
runnable.run();
return true;
}
};
view.getViewTreeObserver().addOnPreDrawListener(preDrawListener);
}
Then call it when u need to get the dimensions
runJustBeforeBeingDrawn(yourView, new Runnable() {
@Override
public void run() {
//Here you can safely get the view size (use "getWidth" and "getHeight"), and do whatever you wish with it
}
});
Related to your question :<br />
View's getWidth() and getHeight() returns 0<br />
Determining the size of an Android view at runtime
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论