我正在尝试扩展一个 android.widget.Button 并向我的自定义小部件添加一个可设置样式的属性,该属性应该包含对 res/values/strings.xml 中的值的引用。
<resources>
<attr name="infoText" format="reference" />
<declare-styleable name="FooButton">
<attr name="infoText" />
</declare-styleable>
</resources
在我的布局中我有这样的东西:
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<com.example.FooButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/fooButton"
infoText="@string/fooButtonInfoText" />
</LinearText>
我的 res/values/strings.xml 看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="fooButtonInfoText">BAR</string>
</resources>
我的自定义 FooButton 中属性值的提取如下所示:
TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.FooButton);
Integer infoTextId = typedArray.getResourceId(R.styleable.FooButton_infoText, 0);
if (infoTextId > 0) {
infoText = context.getResources().getString(infoTextId);
}
typedArray.recycle();
我已经实现了这三个构造函数:
public FooButton(Context context) {
super(context);
}
public FooButton(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
setInfoText(context, attributeSet);
}
public FooButton(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
setInfoText(context, attributeSet);
}
每次声明 FooButton 时都会调用 FooButton.setInfoText(context, attributeSet) 方法。
我与这个问题作斗争太久了,阅读了数十个 Stackoverflow 问题...为什么这不起作用?
最佳答案
您必须为自定义属性声明命名空间。它应该看起来像这样:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/auto"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal">
<com.example.FooButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/fooButton"
app:infoText="@string/fooButtonInfoText" />
</LinearText>
关于android - 在可设置样式的属性中引用字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18421679/