java - android SurfaceView 无法工作

标签 java android surfaceview

这是一个简单的问题,但我无法弄清楚:

这是我的 xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android = "http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
>

<GG.My_pic.testA
        android:id = "@+id/myview"
        android:layout_width = "fill_parent"
        android:layout_height = "fill_parent"
    />

</FrameLayout>

在月球着陆器中,主线程使用

    // tell system to use the layout defined in our XML file
    setContentView(R.layout.lunar_layout);

但是我无法使用我的

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

如果我将 R.layout.main 更改为 --> new testA(this) ,它就可以工作

(testA是扩展SurfaceView实现SurfaceHolder.Callback的类)

为什么?

最佳答案

我发现了原因,但我不知道为什么。

作为 java 和 android 的真正初学者,我花了很长时间才找到答案。

这个问题的关键是

类 gameView 扩展 SurfaceView 实现 SurfaceHolder.Callback {

public gameView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // 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

}

}

你可以看到,这是surfaceview的基础,在每个教程中

比如

http://android-er.blogspot.com/2010/05/android-surfaceview.html

http://www.droidnova.com/playing-with-graphics-in-android-part-ii,160.html

surfaceview中有3种构造函数:

SurfaceView(Context context)
SurfaceView(Context context, AttributeSet attrs)
SurfaceView(Context context, AttributeSet attrs, int defStyle)

我花了一天时间使用第一个:

SurfaceView(Context context)

并且总是“强制关闭”。

但是当我转向第二个构造函数时:

SurfaceView(Context context, AttributeSet attrs)

它突然起作用了!

这就是解决方案。

谁能告诉我为什么?

关于java - android SurfaceView 无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3923927/

相关文章:

android - Kotlin在与 Activity 不同的布局上更新textview的文本

android - 将 TextView 添加到表面 View

java - 相机预览未全屏显示(显示在一个框中)

java - AES - 保证 Java (Android) 支持?

java - 尝试使用 groovy 脚本运行程序在 JIRA 中删除时出现 NullPointerException

java - MySQL 和 JDBC 连接池 : unclosed statements

java - 我的 Hibernate 测试程序在执行期间卡住

java - 如何用Java平滑移动鼠标光标?

android - 条码 fragment (Zxing库)

android - OnDraw() 未触发,在 surfaceView 中未绘制任何内容 - Android