Steven Shih
Steven Shih

Reputation: 645

android surfaceview can't work

it's a easy question, but I can't figure it out:

this is my 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>

In lunar lander, the main thread uses

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

But I can't use my

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

If I change my R.layout.main to --> new testA(this) , it works

(testA is the class that extends SurfaceView implements SurfaceHolder.Callback)

why??

Upvotes: 2

Views: 3949

Answers (1)

Steven Shih
Steven Shih

Reputation: 645

I found out why, but I don't know why.

Being a real beginner in both java and android, I spent a very long time to find out.

The key to this problem is

class gameView extends SurfaceView implements 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

}

}

you can see, that this is the basic of surfaceview, in every tutorial

such as

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

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

There are 3 kinds of constructor in surfaceview:

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

I spent a day using the first one :

SurfaceView(Context context)

and it always comes to "force close".

but when I turned to the second constructor:

SurfaceView(Context context, AttributeSet attrs)

It suddenly works!

This is the solution.

Can anyone tell me why??

Upvotes: 5

Related Questions