我有这个简单的布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <SurfaceView android:id="@+id/surfaceView1" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight = "1" /> <LinearLayout android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button2" /> </LinearLayout> </LinearLayout>
这符合并且应用运行完美.
我想用我自己的自定义SurfaceView替换通用的SurfaceView:
import android.content.Context; import android.view.SurfaceHolder; import android.view.SurfaceView; public class PuzzleView extends SurfaceView implements SurfaceHolder.Callback { public PuzzleView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override public void surfaceChanged(SurfaceHolder holder,int format,int width,int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub } }
并在布局中使用xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <PuzzleView android:id="@+id/surfaceView1" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight = "1" /> . . .
一旦活动创建,我得到一个例外:
public class MyActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); } 10-29 19:56:25.921: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to start activity ComponentInfo{ybz.pack1/ybz.pack1.MyActivity}: android.view.InflateException: Binary XML file line #7: Error inflating class PuzzleView
这是不允许的我找不到任何这样做的例子.
编辑:
除了下面给出的解决方案,还需要将所有的SurfaceView构造函数添加到PuzzleView中:
public PuzzleView(Context context,AttributeSet attrs,int defStyle) { super(context,attrs,defStyle); // TODO Auto-generated constructor stub } public PuzzleView(Context context,AttributeSet attrs) { super(context,attrs); // TODO Auto-generated constructor stub }
解决方法
在您的xml布局中,您还必须编写包(您声明您的类的地方),如下所示:
<com.your.package.here.PuzzleView android:id="@+id/surfaceView1" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight = "1" />