I have class, which extends LinearLayout, in it there are Buttons and a Spinner.
This Object gets included via my layout XML file:
<com.ics.spinn.ComboBox android:id="@+id/myautocombo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:completionThreshold="1"
android:entries="@array/suppliers" />
/>
The array suppliers is defined in strings.xml.
If this component now wouldn’t be com.ics.spinn.ComboBox, but a Spinner, Android would
auto-populate the “android:entries” to the Spinner adapter.
I’d like my component com.ics.spinn.ComboBox to behave the same way:
to be able to access the array defined via the xml file, so I can
supply it to the Spinner inside my component, via:
ArrayAdapter<String> a = new ArrayAdapter<String>(this.getContext(),android.R.layout.simple_spinner_dropdown_item, ARRAYINSIDEMYXML);
s.setAdapter(a);
I now I could access the array defined in strings.xml DIRECTLY via getResources().getStringArray(R.array.suppliers)
but my code shouldn’t know of the name “suppliers”, since it shall be supplied via android:entries…
This + the entries in xml in João Melo solution WORK:
public ComboBox(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray b = context.obtainStyledAttributes(attrs,
R.styleable.ComboBox, 0, 0);
CharSequence[] entries = b.getTextArray(R.styleable.ComboBox_myEntries);
if (entries != null) {
ArrayAdapter<CharSequence> adapter =
new ArrayAdapter<CharSequence>(context,
android.R.layout.simple_spinner_item, entries);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
}
}
I don’t know if it’s possible to do that with
android:entriesattribute unless your component extends Spinner, but I’m only guessing.You can achieve that creating your own custom attribute in attrs.xml
Then you can access this reference (int) inside your component and set the ArrayAdapter into your spinner.
On your layout, add this line
xmlns:app="http://schemas.android.com/apk/res/yourPackageName"belowxmlns:android="http://schemas.android.com/apk/res/android"in the root view:Then you can instantiate your component and custom attrs via xml:
Don’t know if this answer is exactly what you’re looking for but it would behave just like
android:entries. Hope it helps.