Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set layout params dynamically

I'm using the CameraPreview example API demo. I need to add some views (button, etc..) overlaying the SurfaceView.

For this, I'm trying to set their parameters, but they appear all the time on the top-left side of the screen.

This is the onCreate method of the code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        btnTakePhoto = new Button(this);
        btnTakePhoto.setBackgroundResource(android.R.drawable.ic_menu_camera);


        /*Set container*/
        mPreview = new Preview(this);
        setContentView(mPreview);

        /*Set button params and add it to the view*/
        RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        buttonParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        buttonParams.addRule(RelativeLayout.CENTER_VERTICAL);
        addContentView(btnTakePhoto, buttonParams);


        numberOfCameras = Camera.getNumberOfCameras();

        CameraInfo cameraInfo = new CameraInfo();
        for (int i = 0; i < numberOfCameras; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
                defaultCameraId = i;
            }
        }
    }

Have to say that the values here

RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

are updating well if I change them. What doesn't change is what contains the addRule() method

like image 270
masmic Avatar asked Mar 17 '14 15:03

masmic


2 Answers

Finally solved. When doing setContentView() and addContentView(), I was placing the views in a DecorView which is a FrameLayout. So, LayoutParams referencing RelativeLayout won't work, as for a FrameLayout only generic features of LayoutParams will work.

So, the thing is to first create a relativeLayout, set the params and set it as the content:

RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
setContentView(relativeLayout, rlp);

But, now, every time I want to add a view, I have to add it to this relativeLayout this way:

relativeLayout.addView(View, Params);

Just this.

like image 186
masmic Avatar answered Oct 12 '22 23:10

masmic


are you wanna to add the btnTakPhoto to the right center of the view? if so, have a try:

btn.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL);
like image 43
Weibo Avatar answered Oct 12 '22 23:10

Weibo