开发者

super simple custom view

开发者 https://www.devze.com 2023-01-19 16:39 出处:网络
This should be easy but for some reason it isn\'t working.I wanted to figure out how to do custom views, so I started by doing one that simply overrides Button, but adds no functionality, just to make

This should be easy but for some reason it isn't working. I wanted to figure out how to do custom views, so I started by doing one that simply overrides Button, but adds no functionality, just to make sure it works.

Java (file 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 (within 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开发者_StackOverflow社区="100px" android:textStyle="bold" />

If I replace "com.foo.bar.FooButton" with "Button", all is well, and I get my button. If I run it as above, it crashes on startup and in logcat I get:

E/AndroidRuntime( 1411): Caused by: android.view.InflateException: Binary XML file line #11: Error inflating class com.foo.bar.FooButton

Something simple I'm doing wrong?


You have to override the version of the constructor that also takes an AttributeSet:

public Button (Context context, AttributeSet attrs)

This AttributeSet will contain the other values you set in the xml, such as:

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

精彩评论

暂无评论...
验证码 换一张
取 消