Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access a custom view's android:layout_width and android:layout_height parameters?

Tags:

android

view

How do you access your custom view's android:layout_width and android:layout_height values?

Sample xml:

<com.example.CustomButton
    android:id="@+id/btn"
    android:layout_width="150dp"
    android:layout_height="70dp" />

In CustomButton:

@Override
protected void onMeasure(int widthSpec, int heightSpec) {
    int measuredWidth = MeasureSpec.getSize(widthSpec);
    int measuredHeight = MeasureSpec.getSize(heightSpec);
    // How can we measure based on android:layout_width, android:layout_height?
    // Currently this implementation measures off the parent's values
    setMeasuredDimension(measuredWidth, measuredHeight);
}
like image 890
Dude Avatar asked Dec 04 '25 11:12

Dude


1 Answers

You must get the layout params of the view:

CustomButton.LayoutParams viewParams = yourView.getLayoutParams();

And then you can access or modify the width or view:

viewParams.height;
viewParams.width;

Hope it helps!

like image 196
Lucia Avatar answered Dec 07 '25 00:12

Lucia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!