Android自定义下拉视图与动态列表

11 浏览
0 Comments

Android自定义下拉视图与动态列表

我遇到了一个问题,无法使用我的ViewModel中的String[]填充android:entries。代码如下:

attrs.xml


    

我的自定义下拉菜单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 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文件


ViewModel正确地绑定了,我在xml文件中多次使用它。当我尝试运行应用程序时,出现以下错误:

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

当我使用`android:entries="@array/genders"`时,它可以工作,但我需要这个列表是动态的。项目采用MVVM模式。感谢任何帮助 🙂

0
0 Comments

问题出现的原因是需要实现一个具有动态列表的自定义下拉视图。解决方法是使用BindingAdapter来实现。

首先需要在AutoCompleteDropDown中创建一个名为updateData的方法,用于更新数据。

然后,在xml文件中使用app:entries="@{vm.genders}"来设置下拉视图的数据。

最后,在BindingAdapter中添加以下代码:

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

0
0 Comments

问题的出现的原因是开发者想要实现一个自定义的下拉视图(drop down view),并且希望下拉视图的内容根据数据动态生成。

解决方法是使用自定义的AutoCompleteDropDown视图,并在布局文件中使用customNS:entries属性来指定下拉视图的内容。开发者还可以使用customNS命名空间来引用自定义的属性。

代码示例中的AutoCompleteDropDown视图继承自AutoCompleteTextView,它的布局宽度设置为match_parent,高度设置为wrap_content。视图中的文本内容通过双向绑定(data binding)来绑定到vm.title变量上。下拉视图的内容通过vm.genders变量来指定。

开发者可以参考stackoverflow上的示例链接来了解更多关于Android自定义UI和自定义属性的信息。

0