Android 设置SurfaceView';以编程的方式删除页边距

Android 设置SurfaceView';以编程的方式删除页边距,android,layout,surfaceview,Android,Layout,Surfaceview,我正在布局xml文件中添加摄像头的“SurfaceView”,如下所示: <SurfaceView android:id="@+id/preview" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="95dp" android:layout_alignParent

我正在布局xml文件中添加摄像头的“SurfaceView”,如下所示:

<SurfaceView
        android:id="@+id/preview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="95dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"/>

但是我想动态设置marginTop。如果我想以编程方式设置SurfaceView的marginTop,我该怎么做


我在网上搜索过。但我没有得到任何答案。任何人都可以帮我做这件事。

你可以做如下事情:

int margin = getResources().getDimensionPixelSize(R.dimen.surface_view_margin);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
lp.setMargins(margin, 0, 0, 0);
surfaceView.setLayoutParams(lp);

这有帮助吗?

静态和动态表面查看示例我正在使用setLayoutParams,但它在创建等后被覆盖。你知道为什么吗?请阅读我的问题: