kburbach
kburbach

Reputation: 759

Correct way to fetch attributes for custom views?

I'm trying to go about getting the attributes from the xml layout file for my custom view class, and there seems to be two ways to do this.... Is one of these ways better practice or something like that?

This first one is using a Typed array to access all the attributes

    public VisualNode(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub

    //getting all the attributes that might be set in an xml file
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                           R.styleable.VisualNode, 0, 0);       

    String text = a.getString(R.styleable.VisualNode_device_name);
    deviceName = new TextView(context);
    deviceName.setText(text);

versus this one directly accessing the resources

    deviceName = new TextView(context);
    deviceName.setText(R.styleable.VisualNode_device_name);

Upvotes: 0

Views: 98

Answers (1)

DejanRistic
DejanRistic

Reputation: 2039

Using a TypedArray is preferred as accessing the attributes directly has some disadvantages.

The two disadvantages I could find in the Android Documentation are the follwoing:

  • Resource references within attribute values are not resolved
  • Styles are not applied

Take a look at this link from the documentation:

http://developer.android.com/training/custom-views/create-view.html#applyattr

Good Luck!

Upvotes: 1

Related Questions