我有一个扩展按钮的类。我想给它添加一个额外的属性。有什么方法可以从 XML 初始化该属性吗?例如:
<MyButton android:id="@+id/myBtn" myValue="Hello World"></MyButton>
public class MyButton extends Button{
private String myValue = "";
public CalcButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
}
最佳答案
是的。您可以拥有自定义属性并在 XML 中为其分配值。您甚至可以分配方法来处理小部件上的自定义事件。 Long press definition at XML layout, like android:onClick does
所需的步骤。
- 实现您的自定义小部件。
然后在res/values/中添加文件attrs.xml,内容如下:
<xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyButton"> <attr name="myValue" format="string"/> </declare-styleable> </resources>
- 在 MyButton 构造函数中从 XML 中检索值。请记住实现所有构造函数,而不仅仅是一个构造函数。
在布局 xml 中使用新属性:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res/**your.package**" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <your.package.MyButton android:id="@+id/theId" android:layout_width="wrap_content" android:layout_height="wrap_content" custom:myValue="myDoSomething" /> <!-- Other stuff --> </LinearLayout>
关于android - 在 Android 中设置自定义 View 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5672716/