项目需要在一个Activity中显示自定义的View和Android的Button等一般控件,之前使用的方法是在xml中只定义普通控件,然后用LayoutInflater生成View对象,
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mainView = inflater.inflate(R.layout.main, null);
自定义的SurfaceView通过SurfaceView mView = new SurfaceView(this);实现,然后再动态创建布局容器,把两个View对象加进去并显示。但发现不管把自定义的SurfaceView宽和高设置的多大,SurfaceView都会把xml的布局给遮挡住,于是就采用把自定义的SurfaceView也定义在xml文件里,问题解决。但要注意的是在自定义的SurfaceView中必须生成public CameraView(Context context, AttributeSet attrs)两个参数的构造方法,因为第二个参数用来在生成对象时传递宽、高等一些属性,否则会抛异常。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical" >
<cn.zzti.ly.view.CameraView
android:id="@+id/cameraView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/temperature"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:textColor="#ffffff" />
</LinearLayout>