How to use custom attributes in Android View declare-styleable?

In Android, custom View attributes can be defined using declare-styleable. declare-styleable is an XML tag used to define a collection of custom View attributes.

Here are the steps to use declare-styleable:

  1. XML file located in the “res/values” directory.
  2. styleable declaration
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="titleText" format="string" />
        <attr name="subtitleText" format="string" />
        <attr name="titleTextColor" format="color" />
        <attr name="subtitleTextColor" format="color" />
    </declare-styleable>
</resources>
  1. retrieve the styled attributes
public class MyCustomView extends View {
    private String titleText;
    private String subtitleText;
    private int titleTextColor;
    private int subtitleTextColor;
    
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
        
        titleText = a.getString(R.styleable.MyCustomView_titleText);
        subtitleText = a.getString(R.styleable.MyCustomView_subtitleText);
        titleTextColor = a.getColor(R.styleable.MyCustomView_titleTextColor, Color.BLACK);
        subtitleTextColor = a.getColor(R.styleable.MyCustomView_subtitleTextColor, Color.GRAY);
        
        a.recycle();
    }
    
    // ...
}

In the above example, the obtainStyledAttributes method retrieves the attribute values defined in attrs.xml and assigns them to titleText, subtitleText, titleTextColor, and subtitleTextColor.

  1. In the layout file, utilize a custom View and configure its attributes.
<com.example.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:titleText="Title"
    app:subtitleText="Subtitle"
    app:titleTextColor="#FF0000"
    app:subtitleTextColor="#00FF00" />

In the example above, custom attribute values are set using the app: prefix.

By doing this, you can define and use custom View attributes with declare-styleable.

bannerAds