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?
How to programatically resize and show them? Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling. All of these attributes can be set in code on each ImageButton at runtime.
You cannot set text to ImageButton because it has no method as setText() or android:text property. ImageButtons can't have text (or, at least, android:text isn't listed in its attributes). It looks like you need to use Button (and look at drawableTop or setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)) .
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"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With