我在使用 ViewModel
中的 String[]
填充 android:entries
时遇到问题。代码如下:
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);
}
...
View 模型
...
private String[] genders;
public String[] getGenders() {
return genders;
}
public void setGenders(String[] genders) {
this.genders = genders;
}
...
性别
填充在ViewModel
构造函数中:
性别 = 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
已正确绑定(bind),我在该 xml 文件中多次使用它。当我尝试运行该应用程序时,我得到:
Cannot find the setter for attribute 'android:entries' with parameter type java.lang.String[] on AutoCompleteDropDown
当我使用 android:entries="@array/genders"
时它可以工作,但我需要这个列表是动态的。项目采用MVVM模式。感谢任何帮助:)
最佳答案
您可以使用BindingAdapter
来实现此目的。喜欢:
@BindingAdapter("entries")
public static void entries(AutoCompleteDropDown view, String[] array) {
view.updateData(array);
}
updateData
它是您必须在 AutoCompleteDropDown
中创建的方法。
在 xml 中它使用相同的
app:entries="@{vm.genders}"
关于java - Android 自定义下拉 View 与动态列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427615/