自定义SurfaceView时,在xml中添加报错Unable to start activity ComponentInfo
<?xml version="1.0" encoding="utf-8" ?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="fill_parent" > <LinearLayout android:id="@+id/operate" android:layout_height="wrap_content" android:layout_width="wrap_content" android:gravity="center_horizontal"> <Button android:id="@+id/btn_reset" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="重绘" android:layout_marginRight="20dp" /> <Button android:id="@+id/btn_clear" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="清除"/> </LinearLayout> <com.touch.view.MySurfaceView android:id="@+id/view" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout>
解决办法:
如果你的activity显示内容就只是一个surfaceview的话,那么你只重写public mysurfaceview(Context context)就可以,然后在activity的oncreate方法中使用类似于下面的代码加载: setContentView(new MySurfaceView(this));
如果你的SurfaceView是放在一个xml布局文件中比如main.xml中,那么你的SurfaceView中只需要重写public mysurfaceview(Context context, AttributeSet attrs),加载时就要这样: setContentView(R.layout.main);
重写一个构成函数