【问题标题】:How to read custom attributes in Android如何在 Android 中读取自定义属性
【发布时间】:2013-01-15 13:58:03
【问题描述】:

我可以创建自定义属性并将它们应用于常规EditTexts,如下所示:

<EditText
     android:id="@+id/field1"
     custom:attr1="whatever"
     (...)
<EditText
     android:id="@+id/field2"
     custom:attr1="whatever2"
     (...)

我的问题:我可以在不创建扩展EditText 的类的情况下读取这些自定义属性的值吗?我的意思是,我想从Activity 中读取自定义属性,但到目前为止我看到的示例需要我从自定义视图的构造函数中读取值,如下所示:Defining custom attrs

【问题讨论】:

  • 不,你不能这样做。 AttributeSet 在视图构建后丢弃。

标签: java android android-custom-view


【解决方案1】:

我的问题:我可以不读取这些自定义属性的值吗? 创建一个扩展 EditText 的类?

是的,您可以在不扩展类的情况下获得这些属性。为此,您可以在LayoutInflater 上设置一个特殊的FactoryActivity 将使用它来解析布局文件。像这样的:

super.onCreate(savedInstanceState);
getLayoutInflater().setFactory(new CustomAttrFactory());
setContentView(R.layout.the_layout);

CustomAttrFactory 是这样的:

public static class CustomAttrFactory implements Factory {

    @Override
    public View onCreateView(String name, Context context,
            AttributeSet attrs) {
        String attributeValue = attrs
                .getAttributeValue(
                        "http://schemas.android.com/apk/res/com.luksprog.droidproj1",
                        "attrnew");
        Log.e("ZXX", "" + attributeValue);
        // if attributeValue is non null then you know the attribute is
        // present on this view(you can use the name to identify the view,
        // or its id attribute)
        return null;
    }
}

这个想法来自blog post,您可能需要阅读它以获取更多信息。

此外,根据该自定义属性(或其他属性),您可以使用 android:tag="whatever" 传递附加数据(然后在 Activity 中使用 view.getTag() 检索它)。

我建议您不要使用这些自定义属性并重新考虑您当前的方法。

【讨论】:

  • 我喜欢工厂的想法。谢谢!
  • 然后就到这里了 :-( 链接现在坏了。
  • @Nicks 这就是提供外部链接的问题,抱歉。但是,在那篇博文中,它与我在回答中提供的与 LayoutInflater 一起使用的自定义工厂相关的信息基本相同。
  • @Luksprog 但非常感谢,您添加的描述足以跟踪和解决 :-) 非常感谢。我希望这也适用于片段。
【解决方案2】:

我会说不,你不能。我检查了EditText 的来源及其父母,但没有找到将自定义属性存储到实例属性的位置,以便您以后可以使用它们。所以我认为你需要创建自己的类来扩展EditText

【讨论】:

  • 我知道我可以解析 xml 布局并从那里读取值,但必须有一些更简单的方法......
  • @André 是的,创建你自己的类 :) 你为什么不想创建单独的类?
  • 因为我想将相同的属性应用于编辑文本、微调器、复选框等。我不想为每个字段类型创建自定义类
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多