I have designed an layout in which LinearLayout
has 2 children LinearLayout
and FrameLayout
and in each child I put different views.
try with this metods:
int width = mView.getMeasuredWidth();
int height = mView.getMeasuredHeight();
Or
int width = mTextView.getMeasuredWidth();
int height = mTextView.getMeasuredHeight();
I had same issue but didn't want to draw on screen before measuring so I used this method of measuring the view before trying to get the height and width.
Example of use:
layoutView(view);
int height = view.getHeight();
//...
void layoutView(View view) {
view.setDrawingCacheEnabled(true);
int wrapContentSpec =
MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
view.measure(wrapContentSpec, wrapContentSpec);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}
try something like this code from this link
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
viewWidth = view.getWidth();
viewHeight = view.getHeight();
}
});
}
hope this helps.
you can use coroutines as well, like this one :
CoroutineScope(Dispatchers.Main).launch {
delay(10)
val width = view.width()
val height= view.height()
// do your job ....
}
As CapDroid say, you are trying to get the size before the view drawn, another possible solution could be to do a Post with a runnable on the View:
mView.post(new Runnable() {
@Override
public void run() {
int width = mView.getWidth();
int height = mView.getHeight();
}
}
I used DisplayMetrics to get the screen size and then i can assign the width/height to an element in %age
It will be like this
DisplayMetrics dmetrics = new DisplayMetrics();
int widthPixels=dmetrics.widthPixels;
int heightPixels=dmetrics.heightPixels;
//setting the height of the button
button_nextPuzzle.setMinHeight((int) ((heightPixels/3)*.30));
Worked for me very well!!!