Mershel
Mershel

Reputation: 552

Android custom drop down view with dynamic list

I have a problem with filling android:entries with String[] from my ViewModel. Code looks like that:

attrs.xml

<declare-styleable name="AutoCompleteDropDown">
    <attr name="android:entries" />
</declare-styleable>

My custom dropdown, AutoCompleteDropDown

public class AutoCompleteDropDown extends AppCompatAutoCompleteTextView {

    public AutoCompleteDropDown(Context context, AttributeSet attributes) {
        super(context, attributes);
        TypedArray a = context.getTheme().obtainStyledAttributes(attributes, R.styleable.AutoCompleteDropDown, 0, 0);
        CharSequence[] entries = a.getTextArray(R.styleable.AutoCompleteDropDown_android_entries);
        ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(context, android.R.layout.simple_dropdown_item_1line, entries);
        setAdapter(adapter);
    }
...

ViewModel

...
private String[] genders;

public String[] getGenders() {
    return genders;
}

public void setGenders(String[] genders) {
    this.genders = genders;
}
...

genders are filled in ViewModel constructor:

genders = dataRepository.getGenders();

xml file

<AutoCompleteDropDown
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@={vm.title}"
    android:entries="@{vm.genders}"
    bind:addTextChangedListener="@{vm.titleValidationChangeListener}"/>

ViewModel is binded correctly, i'm using it many times in that xml file. When i try to run the app i'm getting:

Cannot find the setter for attribute 'android:entries' with parameter type java.lang.String[] on AutoCompleteDropDown

It works when i use android:entries="@array/genders" but i need this list to be dynamic. Project is in MVVM pattern. Appreciate any help :)

Upvotes: 0

Views: 1454

Answers (2)

Chetan Shelake
Chetan Shelake

Reputation: 686

<AutoCompleteDropDown
    xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@={vm.title}"
    customNS:entries="@{vm.genders}"
 />

You can check this example Android - custom UI with custom attributes

Upvotes: 0

Ivan Krasilnikov
Ivan Krasilnikov

Reputation: 261

You can use BindingAdapter for this. Like :

@BindingAdapter("entries")
public static void entries(AutoCompleteDropDown view, String[] array) {
    view.updateData(array);
}

updateData it's method which you must create in your AutoCompleteDropDown. And in xml it's using same

app:entries="@{vm.genders}"

Upvotes: 2

Related Questions