I have extended the ImageView class in a class called DialButton2 (dont worry about the name of the class, its irrelevant). All the DialButton2 class does is show an arbitrary image located in the drawable folder.
package com.com.com;
import android.content.Context;
import android.widget.ImageView;
import android.util.AttributeSet;
public class DialButton2 extends ImageView{
public DialButton2(Context context) {
super(context);
this.setImageResource(R.drawable.dialpad);
}
public DialButton2(Context context, AttributeSet attrs){
super(context, attrs);
this.setImageResource(R.drawable.dialpad);
}
}
In the XML file for the main activity in my app I specify that a DialButton2 object should be displayed. I give it the id “button1”.
<?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:src="@drawable/dialpad"
android:layout_weight="1"
/>
Dont worry about the rest of the XML-file, its irrelevant.
My problem is that when I try to instantiate a reference to the button in code, eclipse tells me I have to cast it to ImageView. Why is this?
package com.com.com;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
public class Android3 extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maintable);
/*
* The instantiating below gives an error saying I have to cast to ImageView.
*/
DialButton2 button1 = findViewById(R.id.button1);
}
}
You have to cast to DialButton2
findViewById() returns a View, you have to cast it before you can use it as a DialButton2.