具有动态列表的Android自定义下拉视图

时间:2018-11-22 09:25:52

标签: java android xml mvvm dropdown

我在用android:entries中的String[]填充ViewModel时遇到问题。代码如下:

attrs.xml

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

我的自定义下拉菜单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填充在ViewModel构造函数中:

genders = dataRepository.getGenders();

xml文件

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

ViewModel已正确绑定,我在该xml文件中多次使用它。当我尝试运行该应用程序时,我得到了:

  

找不到带有参数的属性“ android:entries”的设置器   在AutoCompleteDropDown上键入java.lang.String []

当我使用android:entries="@array/genders"时可以使用,但是我需要此列表是动态的。项目处于MVVM模式。感谢任何帮助:)

2 个答案:

答案 0 :(得分:2)

您可以为此使用[ { "_id": "Voluptatem perferendis voluptas ex.", "options": [ { "option": "Vero rerum qui animi quia assumenda.", "votes_by_age": [ { "age_group": "25-54 years", "total_votes": 1 }, { "age_group": "55-64 years", "total_votes": 1 }, { "age_group": "65 years and over", "total_votes": 5 } ] }, {...}, ... ] 。像:

BindingAdapter

@BindingAdapter("entries") public static void entries(AutoCompleteDropDown view, String[] array) { view.updateData(array); } 是您必须在updateData中创建的方法。 在xml中使用的是相同的

AutoCompleteDropDown

答案 1 :(得分:0)

<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}"
 />

您可以查看此示例Android - custom UI with custom attributes