2011-06-12 31 views
1

我已經在名爲DialButton2的類中擴展了ImageView類(不用擔心類的名稱,它的不相關)。所有DialButton2類所做的是顯示位於可繪製文件夾中的任意圖像。爲什麼要將擴展的ImageView投影到ImageView?

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); 
    } 

} 

在我的應用程序中的主要活動的XML文件中,我指定應該顯示DialButton2對象。我給它的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" 
     /> 

不要擔心XML文件的其餘部分,它與其無關。

我的問題是,當我嘗試在代碼中實例化按鈕的引用時,eclipse告訴我必須將其轉換爲ImageView。爲什麼是這樣?

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); 
    } 
} 
+0

沒有findViewById()行,您的代碼是否編譯並顯示預期的視圖? – Noel 2011-06-12 15:16:33

+0

XML組件在最後缺少2。另外,XML組件之前沒有完整的包名稱。但問題解決了。 – fred 2011-06-12 22:19:11

回答

2

你要投給DialButton2

DialButton2 button1 = (DialButton2) findViewById(R.id.button1); 

findViewById()返回一個視圖,你必須投它之前,你可以使用它作爲一個DialButton2。

+0

我明白了,歡呼的隊友。 – fred 2011-06-12 18:39:19

1

你要投,因爲getViewById(..)返回View對象。當你從父母班級(View)轉到子班級(ImageView/DialButton2)時,需要進行施放。您可以看到方法詳細信息here

+0

我看,歡呼的隊友。 – fred 2011-06-12 18:38:19

1

天氣還是不是你變得DialButton2是不相關的,因爲無論你嘗試使用findViewById(int)「查找」哪個視圖,你都必須將它轉換到正在初始化的同一個類。

+0

我明白了,歡呼的隊友。 – fred 2011-06-12 18:38:55