18

I'm implementing my own <declare-styleable> for a custom View (following the instructions here). I'd like to be able to specify an array of integers as one of the possible XML attributes. How do I:

  1. Specify the integer array as an XML attribute in attrs.xml?
  2. Get it from the TypedArray after calling obtainStyledAttributes() in my custom View?
XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151

2 Answers2

33
  1. You can declare it as a reference.

    <declare-styleable name="MyView">
        <attr name="array" format="reference"/>
    </declare-styleable>
    
  2. It looks like TypeArray hasn't getIntArray method so you have to get it directly from the resources.

    final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyView);
    final int id = array.getResourceId(R.styleable.MyView_array, 0);
    
    if (id != 0) {
        final int[] values = getResources().getIntArray(id);
    }
    
    array.recycle()
    
Luke
  • 2,187
  • 1
  • 18
  • 29
Vladimir Mironov
  • 30,514
  • 3
  • 65
  • 62
1

Don't have enough reputation to add comments, just want to share the kotlin way, where the extension function handles recycle() call itself.

context.withStyledAttributes(attrs, R.styleable.MyView, defStyleAttr) { 
    val resourceId = getResourceId(R.styleable.MyView_array, 0) 
}
Bharat singh
  • 119
  • 1
  • 6