2011-06-12 54 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