如何读取Android的自定义属性 [英] How to read custom attributes in Android
问题描述
我可以创建自定义属性并将其应用到普通的 EditTexts
,像这样的:
<的EditText
机器人:ID =@ + ID /字段1
定制:attR1位=无所谓
(...)
<的EditText
机器人:ID =@ + ID /域2
定制:attR1位=whatever2
(...)
我的问题:我可以阅读,而无需创建一个扩展类的这些自定义属性的值的EditText
?我的意思是,我想读我的活动自定义属性
,但我看到的例子,到目前为止要求我从一个自定义视图,喜欢这里的构造函数读取值: 定义自定义ATTRS
我的问题:我能读懂的价值没有这些自定义属性 创建一个扩展的EditText类?
是的,你可以得到这些属性无需扩展类。为此,您可以使用一个特殊的工厂
在 LayoutInflater
的活动$设置C $ C>将用于解析布局文件。事情是这样的:
super.onCreate(savedInstanceState);
getLayoutInflater()setFactory(新CustomAttrFactory())。
的setContentView(R.layout.the_layout);
其中 CustomAttrFactory
是这样的:
公共静态类CustomAttrFactory实现厂{
@覆盖
公共查看onCreateView(字符串名称,上下文的背景下,
AttributeSet中的ATTRS){
字符串的AttributeValue = ATTRS
.getAttributeValue(
http://schemas.android.com/apk/res/com.luksprog.droidproj1
attrnew);
Log.e(ZXX,+的AttributeValue);
//如果的AttributeValue非空,那么你知道这个属性是
//这个观点present(可以使用名称来标识的观点,
//或者它的id属性)
返回null;
}
}
这个想法来自一个博客文章,你可能需要阅读它的其他信息。
此外,根据该自定义属性(或属性,如果你有其他的),你可以只使用机器人:标签=无所谓
通过附加数据(后来在活动检索
与 view.getTag()
)。
我劝你不要使用那些自定义属性,并重新审视自己目前的做法。
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"
(...)
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
My question: can I read the value of those custom attributes without creating a class that extends EditText?
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);
where the CustomAttrFactory
is like this:
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.
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屋!