Reputation: 323
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?
Upvotes: 0
Views: 230
Reputation: 554
You can use getWidth
and getHeight
to get dimensions of any view (in this case constraint layout
) at runtime.
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
.
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 :
View's getWidth() and getHeight() returns 0
Determining the size of an Android view at runtime
Upvotes: 1