我正在使用 CameraPreview 示例 API 演示。我需要添加一些 View (按钮等)覆盖 SurfaceView。
为此,我尝试设置它们的参数,但它们始终出现在屏幕的左上角。
这是代码的onCreate方法:
@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;
}
}
}
不得不说这里的值(value)观
RelativeLayout.LayoutParams buttonParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
如果我更改它们,它们会更新得很好。不变的是包含 addRule() 方法的内容
最佳答案
终于解决了。在执行 setContentView() 和 addContentView() 时,我将 View 放在作为 FrameLayout 的 DecorView 中。因此,引用 RelativeLayout 的 LayoutParams 将不起作用,对于 FrameLayout,只有 LayoutParams 的通用功能才起作用。
所以,首先要创建一个 relativeLayout,设置参数并将其设置为内容:
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
setContentView(relativeLayout, rlp);
但是,现在,每次我想添加一个 View 时,我都必须以这种方式将它添加到这个 relativeLayout 中:
relativeLayout.addView(View, Params);
就是这个。
关于android - 动态设置布局参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22458468/