Android自定义下拉视图与动态列表
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); ArrayAdapteradapter = 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模式。感谢任何帮助 🙂
问题的出现的原因是开发者想要实现一个自定义的下拉视图(drop down view),并且希望下拉视图的内容根据数据动态生成。
解决方法是使用自定义的AutoCompleteDropDown视图,并在布局文件中使用customNS:entries属性来指定下拉视图的内容。开发者还可以使用customNS命名空间来引用自定义的属性。
代码示例中的AutoCompleteDropDown视图继承自AutoCompleteTextView,它的布局宽度设置为match_parent,高度设置为wrap_content。视图中的文本内容通过双向绑定(data binding)来绑定到vm.title变量上。下拉视图的内容通过vm.genders变量来指定。
开发者可以参考stackoverflow上的示例链接来了解更多关于Android自定义UI和自定义属性的信息。