我想在不同的程序活动中多次创建一个TextView。与其每次设置属性,不如将属性保存在xml文件中,并在每次向活动中添加TextView时使用它。据我所读,我认为使用下面的代码是可行的。
XmlPullParser parser = resources.getXml();
AttributeSet attributes = Xml.asAttributeSet(parser);
TextView textView = new TextView(this, attributes);我的问题是这是一种有效的方法吗?我的第二个问题是,应该在哪里以及如何保存xml属性?在布局文件夹或值中??有什么不同吗?
谢谢
发布于 2015-09-25 14:44:53
您可以使用多态性,例如,您可以创建TextView类的许多子类,并在需要的地方实例化适当的子类:
public class CustomTextView extends TextView {
public CustomTextView(Context context) {
super(context);
init();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
// your custom attributes
// for example
setTextColor(Color.BLACK);
}
}并以这种方式实例化它:
TextView textView = new CustomTextView(this);或您可以从xml布局( take a look )中膨胀视图
https://stackoverflow.com/questions/32784433
复制相似问题