Reading custom attributes

obtainStyledAttributes API

My previous article on custom attributes


public CircleView(Context context) {
        super(context);
        initCircleView();
    }
   public CircleView(Context context, int inStrokeWidth, int inStrokeColor) {
        super(context);
        strokeColor = inStrokeColor;
        strokeWidth = inStrokeWidth;
        initCircleView();
    }
   
    public CircleView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }
    
   //Meant for derived classes to call
   public CircleView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray t = context.obtainStyledAttributes(attrs,R.styleable.CircleView, defStyle,0);
        strokeColor = t.getColor(R.styleable.CircleView_strokeColor, strokeColor);
        strokeWidth = t.getInt(R.styleable.CircleView_strokeWidth, strokeWidth);
        t.recycle();
        initCircleView();
    }

Get it from the attribute set. If an attribute is not found, look in the current theme for a set of attributes identified the style name or id "defStyle". If it is not there let it go. A class could supply its own style resource as the fourth argument (we used 0 there).

Remember a style resource is essentially a collection of attributes and their values.


<resources>
<declare-styleable name="CircleView">
    <attr name="strokeWidth" format="integer"/>
    <attr name="strokeColor" format="color|reference" />
</declare-styleable>
</resources>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:apptemplate="http://schemas.android.com/apk/res/com.androidbook.custom"    
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    >
...
<com.androidbook.custom.CircleView
   android:id="@+id/circle_view_id"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"
    apptemplate:strokeWidth="5"
    apptemplate:strokeColor="@android:color/holo_red_dark" 
    />    
....
</LinearLayout>

<resources>
<declare-styleable name="CircleView">
    <attr name="strokeWidth" format="integer"/>
    <attr name="strokeColor" format="color|reference" />
</declare-styleable>
<declare-styleable name="DurationComponent">
    <attr name="durationUnits">
      <enum name="days" value="1"/>
      <enum name="weeks" value="2"/>
    </attr>
</declare-styleable>
</resources>

Why ids generated in R.java for enumerations in attrs.xml

Search for: Why ids generated in R.java for enumerations in attrs.xml