TextView的Android自定义属性
可能重复:
如何在Android中阅读自定义属性
最近我读到了自定义属性。 我想为TextView添加自定义属性。
到目前为止我有:
attr文件:
布局文件:
给出TextView
TextView tv = ...
那么我如何得到该属性的值(这是“测试”)? 我读到了关于obtainStyledAttributes但是不知道如何在这里使用它。
据我所知,你有两个选择:
- 创建自己的视图,扩展
TextView
并具有接受AttributeSet
构造函数。 然后,您可以在此构造函数中获取自定义属性。 查看本教程: 创建视图类 。 - 实现自己的LayoutInfalter.Factory ,您可以在其中处理自定义属性。
更好地检查这个问题: 如何在Android中阅读自定义属性几乎相同。
确切地说,您可以像这样扩展您的文本视图
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: