문제

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.

도움이 되었습니까?

해결책

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...

다른 팁

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(); 

    } 
});

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'

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top