Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom view in xml layout

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.

like image 502
monoceres Avatar asked Jul 15 '10 23:07

monoceres


1 Answers

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

like image 170
Rich Schuler Avatar answered Oct 01 '22 08:10

Rich Schuler