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?
Asked
Active
Viewed 181 times
0
-
2Does this answer your question? https://stackoverflow.com/a/3594216/2410641 – ashu Sep 30 '20 at 16:10
-
1Yes thanks, it solved the issue. I was calling getwidth and getheight in OnCreate which was returning 0, so I thought there might be some other possible way for it. – Obaid Ur Rehman Sep 30 '20 at 17:49
1 Answers
1
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

First dev
- 495
- 4
- 17
-
1This solved my issue. I was calling getwidth and getheight in OnCreate which was returning 0, so I thought there might be some other possible way for it. – Obaid Ur Rehman Sep 30 '20 at 17:49