可能的重复:
如何读取Android中的自定义属性
最近我读到了有关自定义属性的内容。我想向 TextView 添加自定义属性。
到目前为止我有:
属性文件:
<resources>
<attr name="binding" format="string" />
<declare-styleable name="TextView">
<attr name="binding" />
</declare-styleable>
布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res/de.innosoft.android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
custom:binding="test"/>
给定一个 TextView
TextView tv = ...
然后我如何获取该属性的值(即“测试”)?我读到了obtainStyledAttributes,但不知道如何在这里使用它。
确切地说,你可以像这样扩展你的文本视图
public class CustomTV extends TextView {
public final String YOURATTRS;
public CustomTV(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CustomTV);
YOURATTRS = ta.getString(R.styleable.CustomTV_binding);
ta.recycle();
// use your attrs or not
}
和 attrs.xml :
<declare-styleable name="CustomTV">
<attr name="binding" format="string"/>
</declare-styleable>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)