如何在Android中读取自定义属性 [英] How to read custom attributes in Android
问题描述
我可以创建自定义属性并将它们应用于常规的 EditTexts
,如下所示:
I can create custom attributes and apply them to regular EditTexts
, like this:
<EditText
android:id="@+id/field1"
custom:attr1="whatever"
(...)
<EditText
android:id="@+id/field2"
custom:attr1="whatever2"
(...)
我的问题:我可以在不创建扩展 EditText
的类的情况下读取这些自定义属性的值吗?我的意思是,我想从我的 Activity
中读取自定义属性,但是我目前看到的示例要求我从自定义视图的构造函数中读取值,例如:定义自定义属性
My question: can I read the value of those custom attributes without creating a class that extends EditText
? I mean, I want to read custom attributes from my Activity
, but the examples I see so far requires me to read the values from the constructor of a custom view, like here: Defining custom attrs
推荐答案
我的问题:我可以不读取这些自定义属性的值吗?创建一个扩展 EditText 的类?
My question: can I read the value of those custom attributes without creating a class that extends EditText?
是的,您无需扩展类即可获得这些属性.为此,您可以在 LayoutInflater
上使用一个特殊的 Factory
集,Activity
将使用它来解析布局文件.像这样:
Yes, you can get those attributes without extending the classes. For this you could use a special Factory
set on the LayoutInflater
that the Activity
will use to parse the layout files. Something like this:
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;
}
}
这个想法来自 博文,您可能需要阅读它以获取更多信息.
The idea comes from a blog post, you may want to read it for additional information.
此外,根据自定义属性(或其他属性),您可以只使用 android:tag="whatever"
传递附加数据(然后在 Activity
和 view.getTag()
).
Also, depending on that custom attribute(or attributes if you have other) you could just use android:tag="whatever"
to pass the additional data(and later retrieve it in the Activity
with view.getTag()
).
我建议您不要使用这些自定义属性并重新考虑您当前的方法.
I would advise you to not use those custom attributes and rethink your current approach.
这篇关于如何在Android中读取自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!