setContentView()调用SurfaceView布局文件出错的解决方法

看了《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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值