jofftiquez
jofftiquez

Reputation: 7708

Layout params getWidth() returns zero

i have a RelativeLayout here's the code :

<RelativeLayout
   android:id="@+id/camerapreview"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="10dp"
   android:background="#000">
</RelativeLayout>

its a camera preview for the camera application, i set the width to match_parent.

and here is my java code :

RelativeLayout preview = (RelativeLayout) findViewById(R.id.camerapreview);
int w = preview.getWidth();
LayoutParams params = preview.getLayoutParams();
params.width = w;
params.height = w;
preview.addView(mPreview);

basically i decalaired the width of the RelativeLayout to match_parent to be dynamic to the width of any device. But i want the view to be square so i used the java code abave, but every time i ran the program this line int w = preview.getWidth(); returns zero. I must have missed something, help please :D thank you.

Upvotes: 1

Views: 5201

Answers (3)

Shayan Pourvatan
Shayan Pourvatan

Reputation: 11948

The size of view cannot be calculated until its parent is calculated you can force that with following code:

view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int widht = view.getMeasuredWidth();
int height = view.getMeasuredHeight();

there is three way to do this, see this link

EDIT

you can use this too.

RelativeLayout layout = (RelativeLayout) findViewById(R.id.camerapreview); 
ViewTreeObserver vto = layout.getViewTreeObserver(); 
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
    @Override 
    public void onGlobalLayout() { 
        hs.getViewTreeObserver().removeGlobalOnLayoutListener(this); 
        int width  = layout.getMeasuredWidth();
        int height = layout.getMeasuredHeight(); 

    } 
});

Upvotes: 3

Gopal Gopi
Gopal Gopi

Reputation: 11131

this may help you...

    RelativeLayout preview = (RelativeLayout) findViewById(R.id.camerapreview);
    int width = getResources().getDisplayMetrics().widthPixels;
    ViewGroup.LayoutParams params = preview.getLayoutParams();
    params.width = width;
    params.height = width;
    preview.setLayoutParams(params);

here preview will occupy entire screen width... and it will be square shaped...

Upvotes: 2

user2556552
user2556552

Reputation:

Layout has width 'match parent' . So if it hasn't views (is empty) width = 0.
Solution:
Add views to layout
Or set width to 'fill parent'

Upvotes: 1

Related Questions