【问题标题】:Android custom drop down view with dynamic list带有动态列表的Android自定义下拉视图
【发布时间】:2018-11-22 09:25:52
【问题描述】:

我在用我的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);
    }
...

视图模型

...
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 模式。感谢任何帮助:)

【问题讨论】:

    标签: java android xml mvvm dropdown


    【解决方案1】:

    您可以为此使用BindingAdapter。喜欢:

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

    updateData 这是您必须在AutoCompleteDropDown 中创建的方法。 在 xml 中它使用相同的

    app:entries="@{vm.genders}"
    

    【讨论】:

      【解决方案2】:
      <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

      【讨论】:

        猜你喜欢
        • 2011-07-25
        • 2016-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-20
        • 2013-03-10
        相关资源
        最近更新 更多