android - 在可设置样式的属性中引用字符串值

标签 android android-layout android-xml

我正在尝试扩展一个 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/

相关文章:

java - Android 上的 ScheduledExecutorService 行为

java - Room 数据库中的项目未显示在 RecyclerView 中

java - 未知警告图标 - Android Studio

Android自定义对话框显示android标题栏

android - 如何为 guice 3.0 配置 ivy.xml 以使用 no aop jar?

java - Android ListView 绑定(bind)到自定义类

android - 在 Android 中保存动态生成的 UI(是否使用 Sqlite?)

java - (Android) 如何使用Java以编程方式设置colors.xml数据?

android - 访问@android :id/list ListView from code

Android - 在 mipmap 与 drawable 文件夹中存储图像