views:

62

answers:

1

I've created my own view by creating a subclass of the SurfaceView class.

However I can't figure out how to add it from the xml layout file. My current main.xml looks like this:

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

<View
    class="com.chainparticles.ChainView"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent" 
    />


</LinearLayout>

What have I missed?

Edit

More info

My view looks like this

package com.chainparticles;
public class ChainView extends SurfaceView implements SurfaceHolder.Callback {
    public ChainView(Context context) {
        super(context);
        getHolder().addCallback(this);
    }
// Other stuff
}

And it works fine like this:

ChainView cview = new ChainView(this);
setContentView(cview);

But nothing happens when trying to use it from the xml.

+2  A: 

You want:

<?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.chainparticles.ChainView
      android:layout_width="fill_parent"
      android:layout_height="fill_parent" 
     />
</LinearLayout>

Edit:

After seeing the rest of your code it's probably throwing because you can't call getHolder in the constructor while being inflated. Move that to View#onFinishInflate

So:

@Override
protected void onFinishInflate() {
    getHolder().addCallback(this);
}

If that doesn't work try putting that in an init function that you call in your Activitys onCreate after setContentView.

It was probably working before because when inflating from xml the constructor: View(Context, AttributeSet) is called instead of View(Context).

Qberticus
With my first layoutI just recieved a black screen, with this the app crashes instead.
monoceres
what was the stack trace?
Qberticus
http://pastebin.com/u2t3jdMt
monoceres
Maybe these extra suggestions will help.
Qberticus
I got it! The key was that the xml called the constructor with Context and AttributeSet (as you said), so adding that constructor solved it. Thank you very much!
monoceres