【问题标题】:android surfaceview can't work安卓surfaceview不能工作
【发布时间】:2010-10-13 13:06:00
【问题描述】:

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

这是我的 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 surfaceview


    【解决方案1】:

    我找到了原因,但我不知道为什么。

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

    这个问题的关键是

    class 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)
    

    它突然起作用了!

    这就是解决方案。

    谁能告诉我为什么?

    【讨论】:

    • 啊哈!当从 XML 创建时,Android 框架使用 2 个参数构造视图,我猜 AttributeSet 包含定义它的 XML 节点中的所有属性。有关详细信息,请参阅developer.android.com/reference/android/util/AttributeSet.html。这也引起了我的注意。
    • rq 是对的,这是因为你在xml中定义了布局,布局膨胀器会使用第二或第三个变体来构造视图。构造函数的第一个变体有时也很有用,当您在编程代码中手动构造并添加到视图时。
    猜你喜欢
    • 2012-02-28
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多