超简单的自定义视图

时间:2010-10-07 20:26:44

标签: android

这应该很容易,但由于某种原因,它不起作用。我想弄清楚如何做自定义视图,所以我开始做一个简单地覆盖Button,但没有添加任何功能,只是为了确保它有效。

Java(文件FooButton.java):

package com.foo.bar;

import android.content.Context;
import android.widget.Button;

public class FooButton extends Button {

     public FooButton(Context context) {
        super(context);
    }
}

XML(在main.xml中):

<view class="com.foo.bar.FooButton"
android:text="blah" android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:id="@+id/buttonFoo" 
android:textSize="24px" android:paddingLeft="16px"
android:width="100px" android:textStyle="bold" />

如果我用“Button”替换“com.foo.bar.FooButton”,一切都很好,我拿到了我的按钮。如果我按上面那样运行它,它在启动时崩溃,在logcat中我得到:

E / AndroidRuntime(1411):引起:android.view.InflateException:二进制XML文件行#11:错误膨胀类com.foo.bar.FooButton

简单的我做错了吗?

1 个答案:

答案 0 :(得分:2)

您必须覆盖也采用AttributeSet的构造函数的版本:

public Button (Context context, AttributeSet attrs)

此AttributeSet将包含您在xml中设置的其他值,例如:

android:text="blah" android:layout_width="wrap_content"