Android SurfaceView和错误膨胀类
我试图制作一个具有自定义视图的应用程序,但我一直得到“错误膨胀类”。 当涉及到自定义视图时,我肯定缺少一些基本知识,但我不确定是什么。这是一个带有自定义视图的非常简单的程序,还需要什么才能使它工作 (注意:为了回答这个问题,我将SurfaceView类放在Activity类中。在更大的应用程序中,情况并非如此。我没有在此处显示AndroidManifest.xml文件,但它只是由eclipse中的向导生成的。) 以下是java:Android SurfaceView和错误膨胀类,android,surfaceview,Android,Surfaceview,我试图制作一个具有自定义视图的应用程序,但我一直得到“错误膨胀类”。 当涉及到自定义视图时,我肯定缺少一些基本知识,但我不确定是什么。这是一个带有自定义视图的非常简单的程序,还需要什么才能使它工作 (注意:为了回答这个问题,我将SurfaceView类放在Activity类中。在更大的应用程序中,情况并非如此。我没有在此处显示AndroidManifest.xml文件,但它只是由eclipse中的向导生成的。) 以下是java: package com.mypackage; import an
package com.mypackage;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceView;
public class SimpleCustomViewActivity extends Activity {
class TheView extends SurfaceView{
private static final String TAG = "TheView";
public TheView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.i(TAG,"TheView(" + context + "," + attrs + ")");
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_layout);
TheView v = (TheView) findViewById(R.id.myview);
}
}
以下是文件res/layout/simple_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.mypackage.SimpleCustomView.TheView
android:id="@+id/myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
在xml中,它应该是:
<com.mypackage.SimpleCustomView.TheView
android:id="@+id/myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</com.mypackage.SimpleCustomView.TheView>
虽然我还没有测试过,但我相信类似的方法可能会奏效:
<View
class="com.mypackage.SimpleCustomView$TheView"
id="@+id/myview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
从xml文件调用自己的surfaceView类时,需要添加以下公共surfaceView创建方法:
public GameView(Context context) {
super(context);
init(context);
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
如果您正在使用函数setContentView(gv),则只需要第一个函数
: declare two methods and it should be public!!
公共视图(上下文)
public视图(上下文、属性集属性)我更改了简单视图应用程序以反映您的建议。它仍然崩溃了。在com.mypackage.SimpleCustomViewActivity.TheView上,有一个很长的堆栈跟踪,最初似乎是由ClassNotFoundException设置的。所以我也试着公开这个类,但它还是崩溃了。另外,我注意到我们都写了com.mypackage.SimpleCustomView,而我们的意思是com.mypackage.SimpleCustomView。但是这个特定的错误似乎从未出现在我测试的源代码中,并且一定是在我将其复制到这个web表单时引入的。我让它工作了。我不得不将视图移到另一个文件中,而不是将其作为子类。非常感谢你的帮助。最简单的事情有时会折磨开发人员几个小时。我真希望在编译时捕获上述错误。是的,路径com.mypackage.SimpleCustomView.TheView指向一个单独的文件类TheView。如果它是活动中的一个内部类,那么就不应该使用XML,而应该使用setContentView(newtheView(this))或someParentLayout.addView(newtheView(this))