Just going to piggyback off your question here, since your post shows up first if you google something like “array reference XML attribute custom view”, so someone might find this helpful.
If you want your custom view to reference an array of strings, you can use Android’s existing android:entries
XML attribute, instead of creating a totally new custom attribute.
Just do the following in res/values/attrs.xml
:
<resources>
<declare-styleable name="MyCustomView">
<attr name="android:entries" />
</declare-styleable>
</resources>
Then do this in your custom View’s constructor:
public MyCustomView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
try
{
CharSequence[] entries = a.getTextArray(R.styleable.MyCustomView_android_entries);
if (entries != null)
{
//do something with the array if you want
}
}
finally
{
a.recycle();
}
}
And then you should be able to reference a string array via the android:entries
attribute when you add your custom View to an XML layout file. Example:
<com.example.myapp.MyCustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/my_array_of_strings" />
This is exactly how it is done in the ListView class (look in the source, you’ll see).