java - Android 自定义下拉 View 与动态列表

标签 java android xml mvvm dropdown

我在使用 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/

相关文章:

android - 尝试更新到 Kotlin 1.4.0 时出现奇怪的错误。如何使其与 Gradle 和 IntelliJ IDEA 2020.2.1 一起使用?

android - hashmap 在 simpleadapter 中工作但在自定义数组适配器中不起作用

android - 抖动错误: Exception: type 'int' is not a subtype of type 'String'

android - 不同类型的解析

c# - 如何检查 XML 值是否存在?

java - 在 Java 中,多少个 Future 才算太多?

java 检测文件是否为UTF-8或Ansi

java - NodeJS 和 Java 创建 REST API

java - 如何修改我的方法以在 O(N) 或 O(N * log N) 中搜索然后删除重复项?

java - 如何使用 JAXB 将缺失的元素解码为空对象