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

And*_*dré 5 java android android-custom-view

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

<EditText
     android:id="@+id/field1"
     custom:attr1="whatever"
     (...)
<EditText
     android:id="@+id/field2"
     custom:attr1="whatever2"
     (...)
Run Code Online (Sandbox Code Playgroud)

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

Luk*_*rog 7

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

是的,您可以在不扩展类的情况下获取这些属性.为此,你可以使用一个特殊Factory的设置LayoutInflater,该Activity将用于解析布局文件.像这样的东西:

super.onCreate(savedInstanceState);
getLayoutInflater().setFactory(new CustomAttrFactory());
setContentView(R.layout.the_layout);
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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