2011-06-12 58 views
8

我想擴展ImageButton類的功能,在我選擇調用「DialButton」的新類中。首先,我簡單地擴展ImageButton,並且沒有添加任何新內容。在我看來,這應該與普通的ImageButton類相同。如何正確地擴展ImageButton?

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 
    } 

} 

我插入XML(不要擔心有關文件的其餘部分,它無關)

<?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"/> 

一個DialButton而在我的活動使用XML:

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

一切編譯並安裝在模擬器中,但是當應用程序啓動時,它強制關閉我。如果我將XML組件從DialButton更改爲ImageButton,則一切正常。爲什麼是這樣? ImageButton類和導致DialButton組件崩潰應用程序的DialButton類有什麼區別?

回答

11

在你的佈局文件,你必須爲你的自定義小部件提供一個「完全合格」的名稱如下...

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

請參閱此鏈接http://developer.android.com/guide/ topics/ui/custom-components.html#修改詳情 – Noel 2011-06-12 21:50:02

+0

乾杯隊友!有效!我忽略了教程的這一部分。在這裏找到:http://developer.android.com/guide/topics/ui/custom-components.html – fred 2011-06-12 21:55:05

+0

@fred:高興地幫助。 – Squonk 2011-06-12 21:58:43