看了《Android游戏编程之从零开始》后,最近在尝试做一个Android小游戏,使用了SurfaceView游戏框架,一开始是在MainActivity的onCreate()中用的下面代码:
setContentView(new MySurfaceView(this));
后来因为想加入有米广告赚点零花钱,所以需要让MySurfaceView与广告的组件同时存在,因此修改了activity_main.xml,把自定义的MySurfaceView也加入进去:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="cloudchen.dodgeball.MainActivity">
<PackageName.MySurfaceView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="@+id/adLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true">
</LinearLayout>
</RelativeLayout>
在onCreate()中也相应修改成了:
setContentView(R.layout.activity_main);
但在运行的时候出现了问题:
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class PackageName.MySurfaceView
经过网上搜查,最终发现是MySurfaceView的构造函数出了问题。
//public MySurfaceView(Context context) { super(context); }
public MySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); }
xml初始化的时候会调用两个参数的构造函数,因此用一个参数的会出问题。同样自定义的View也有相同的问题。
更详细的解释请参考:http://blog.csdn.net/xiaominghimi/article/details/6099194