0

I would like to create a TextView multiple times in different activities programmaticly. Instead of setting the attributes each time, I was thinking I may be able to save the attributes in an xml file and just use it each time I add a TextView to an activity. From what I read I think using the following code would work.

XmlPullParser parser = resources.getXml();
AttributeSet attributes = Xml.asAttributeSet(parser);
TextView textView = new TextView(this, attributes);

My qustion is this a valid way to do it? and my second question is where and how should the xml attributes be saved? in Layout folder or values?? does it make a difference?

Thank you

Ammar Samater
  • 529
  • 2
  • 7
  • 24

1 Answers1

2

You can use polymorphism instead, for example you can create many subclasses of TextView class and instantiate appropriate subclass where you want:

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);
    }
}

and instantiate it in this this way:

TextView textView = new CustomTextView(this);

Or you can inflate Views from xml layout - take a look

Community
  • 1
  • 1
Vasyl Glodan
  • 556
  • 1
  • 6
  • 22