Search code examples
androidxmlextendimagebutton

How to extend ImageButton correctly?


I want to extend the functionality of the ImageButton class, in a new class I choose to call "DialButton". To start off, I simpy extend ImageButton, and added nothing new. In my mind, this should be identical to the normal ImageButton class.

package com.com.com;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;

public class DialButton extends ImageButton{

    public DialButton(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public DialButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    public DialButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

}

I insert a DialButton in XML (dont worry about the rest of the file, its irrelevant)

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1">
    <TableRow
    android:layout_weight="1">
        <DialButton
            android:id="@+id/button1"
            android:background="@drawable/dialpad"
            android:layout_weight="1"/>

And use the XML in my activity:

package com.com.com;

import android.app.Activity;
import android.os.Bundle;

public class Android3 extends Activity {

    DialButton button1;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.maintable);   
    }
}

Everything compiles and installs in the emulator but when the app starts it force closes on me. If I change the XML component from a DialButton to an ImageButton, everything works fine. Why is this? What is the difference between the ImageButton class and my DialButton class that causes the DialButton component to crash the app?


Solution

  • In your layout file, you have to provide a 'fully-qualified' name for your custom widgets as follows...

    <com.mycompany.myapp.DialButton
        android:id="@+id/button1"
        android:background="@drawable/dialpad"
        android:layout_weight="1"/>