如何在Android中读取自定义属性



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

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

我的问题:我可以读取这些自定义属性的值而不创建扩展EditText的类吗?我的意思是,我想从我的Activity中读取自定义属性,但到目前为止我看到的例子要求我从自定义视图的构造函数中读取值,就像这里:定义自定义属性

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

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

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;
    }
}

这个想法来自一篇博客文章,你可能想要阅读它以获得更多信息。

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

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

我会说不,你不能。我检查了EditText的来源和它的父母,没有发现它存储自定义属性到实例属性的地方,所以你可以以后使用它们。所以我认为你需要创建自己的类扩展EditText

最新更新