views:

93

answers:

1

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??

+1  A: 

Hey, guys.

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??

Steven Shih
Aha! The Android framework constructs the View with 2 arguments when created from XML, I guess the AttributeSet contains all the attributes in the XML node that defines it. See http://developer.android.com/reference/android/util/AttributeSet.html for details. This caught me out a few times too.
rq
Thanks, man. You really helped!
Steven Shih
rq is right, this is because you defined the layout in xml, and layout inflater will use the second or third variant to construct the view. The first variant of the constructor is sometimes useful as well, that when you manually construct and add to view in programming codes.
xandy