How to create a simple custom View?

Jonas picture Jonas · Dec 14, 2010 · Viewed 23.9k times · Source

I would like to create an custom View on Android. I have tried to do it as simple as possible and created an almost empty class MyView and used it in my LinearLayout but the application fails on start with "Force Close". How can I do a simple custom View? According to Building Custom Components the View gets the size 100x100 if I don't override onMeasure().

public class MyView extends View {

    public MyView(Context context) {
        super(context);
    }
}

And I use it in a LinearLayout with:

<view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0" />

What am I doing wrong?


If I use the constructor that itemon suggest and the corresponding call to the superclass. Then the "Force Close" is gone, but my LinearLayout is broken, the components after MyView isn't shown.

Here is my main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#f00"
    android:text="Hello"
/>
<view
    class="com.example.MyView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.0"
    android:background="#00f"
    android:text="World"
/>
</LinearLayout>

Answer

itemon picture itemon · Dec 14, 2010

may be you could define another constructor method like this:

public MyView(Context context, AttributeSet attrs)

the android framework will try to build the UI with your view from the constructor above.