Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get RelativeLayout dimensions

How do I get the measurements of a certain layout like linearlayout or relativelayout with its layout_width and layout_height set to wrap_content? using this method

 layout.measure(MeasureSpec.makeMeasureSpec(0,
            MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED));

 layout.layout(0, 0,
            layout.getMeasuredWidth(),
            layout.getMeasuredHeight());

returns null. I'm trying to create a bitmap image out of the relativelayout, kinda like a screenshot.

like image 342
louieansonng Avatar asked Feb 02 '26 19:02

louieansonng


2 Answers

Don't do it on the onCreate() method. Try this:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus == true) {
        LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
        int layoutWidth = myLinearLayout.getWidth();
        int layoutHeight = myLinearLayout.getHeight();
    }
}

This method is called after onCreate(), when the sizes are already known.

like image 95
Xithias Avatar answered Feb 04 '26 10:02

Xithias


You can use getMeasuredWidth() and getMeasuredHeight() on your view.

Remember the view has to have been layout first. You just CANNOT do it in onCreate, because the sizes are not known yet. You have to wait until it has been layout.

like image 30
Jean Avatar answered Feb 04 '26 11:02

Jean



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!