使用XML的Android Spinner数据绑定并显示选定的值 [英] Android spinner Data Binding using XML and show the selected values

查看:125
本文介绍了使用XML的Android Spinner数据绑定并显示选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的android数据绑定,效果很好.我能够使用EditText,TextView,Radio和复选框执行数据绑定.现在,我无法在微调器中进行数据绑定.

I am using the new android data binding and it works great. I am able to perform data binding using EditText, TextView, Radio and checkbox. Now, I am not able to do the databinding in spinner.

在以下链接中找到了一些线索: 具有xml布局的Android微调器数据绑定

Found some clue in below link: Android spinner data binding with xml layout

但是,仍然找不到解决方案.还需要执行两种方式的数据绑定.应该反映出微调器数据的选定值.

But, still not able to find the solution. Also need to perform the two way databinding. Should reflect the spinner data selected value.

有人可以举个例子给我看吗?

Can someone please show me with an example?

这是我的xml代码:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/tools"
    xmlns:card_view="http://schemas.android.com/apk/res-auto">

    <data>
        <import type="android.view.View" />
        <variable
            name="viewModel"
            type="com.ViewModels.model" />
    </data>

     <Spinner
                    android:id="@+id/assessmemt_spinner"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_margin="@dimen/carview_margin"
                    android:layout_toRightOf="@+id/text_bp"
                    android:drawSelectorOnTop="true"
                    android:spinnerMode="dropdown"
                   android:visibility="@{viewModel.type.equals(@string/spinner_type)?  View.VISIBLE : View.GONE}" />
</layout>

查看模型:

 public class AssessmentGetViewModel {
    private String valueWidth;
    private ArrayList<String> values;
    private String type;
    public String getValueWidth() { return this.valueWidth; }
    public void setValueWidth(String valueWidth) { this.valueWidth = valueWidth; }
    public ArrayList<String> getvalues() { return this.values; }
    public void setvalues(ArrayList<String> values) { this.values = values; }
    public String gettype() { return this.type; }
    public void settype(String type) { this.type = type; }
    }

推荐答案

我发现某些东西可能会有所帮助,但在双向数据绑定的官方文档中却没有.

I found somethings might be helpful but it is not in the official documentation for the two-way data binding.

1.双向数据绑定的"@ ="用法

2.双向自定义数据绑定需要使用"BindingAdapter"和"InverseBindingAdapter"批注来实现.

对于第一个项目,许多博客作者展示了双向数据绑定使用"@ ="的情况. https://halfthought.wordpress.com/2016/03/23/2-way-data-binding-on-android/

For the first item, lots of blogger showed the usage of "@=" for two way data binding. https://halfthought.wordpress.com/2016/03/23/2-way-data-binding-on-android/

对于第二项,@ George Mound在这里回答(

For the second item, as @George Mound replied here (Edit text cursor resets to left when default text of edittext is a float value) the EditText can be bind in two-way using "BindingAdapter" and "InverseBindingAdapter" annotation.

按照说明进行操作,您可以为旋转器建立双向绑定方法.

Following the instructions, you can build up your two-way binding method for spinner.

首先,创建您的ViewModel或使用Pojo

Firstly, create your ViewModel or use Pojo

ViewModel

ViewModel

public class ViewModel {
    private ObservableField<String> text;
    public ViewModel() {
        text = new ObservableField<>();
    }
    public ObservableField<String> getText() {
        return text;
    }
}

Pojo

public class ViewModel {
    private String text;
    public String getText() {
        return text;
    }

    public void setText(String text)
    {
       this.text = text;
    }
}

第二,将其添加到您的xml中.

Secondly, add it into your xml.

  <android.support.v7.widget.AppCompatSpinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:entries="@array/days"
            bind:selectedValue="@={viewModel.text}"/>

第三,添加您的bindingUtil

Thirdly, add your bindingUtil

public class SpinnerBindingUtil {

    @BindingAdapter(value = {"selectedValue", "selectedValueAttrChanged"}, requireAll = false)
    public static void bindSpinnerData(AppCompatSpinner pAppCompatSpinner, String newSelectedValue, final InverseBindingListener newTextAttrChanged) {
        pAppCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                newTextAttrChanged.onChange();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        if (newSelectedValue != null) {
            int pos = ((ArrayAdapter<String>) pAppCompatSpinner.getAdapter()).getPosition(newSelectedValue);
            pAppCompatSpinner.setSelection(pos, true);
        }
    }
    @InverseBindingAdapter(attribute = "selectedValue", event = "selectedValueAttrChanged")
    public static String captureSelectedValue(AppCompatSpinner pAppCompatSpinner) {
        return (String) pAppCompatSpinner.getSelectedItem();
    }

}

如您所见,它使用"selectedValue"作为默认选择值的变量,但是"selectedValueAttrChanged"是什么?我以为这很棘手(我不知道为什么它在调用时不为null),不需要在xml中添加,因为它只是用于监听在其中更改的项的回调微调器.然后设置onItemSelectedListener并将其设置为调用InverseBindingListener onchange()函数(此处的文档和示例:

As your saw, it used "selectedValue" as variable for the default selected value, but what is "selectedValueAttrChanged" ?? I thought this one is tricky(I dunno why it is not null when it is called) , it is not need to be added in the xml since it is only the callback for listening the item changed in the spinner. And then you set the onItemSelectedListener and set it to call InverseBindingListener onchange() function (Documentation and example here : https://developer.android.com/reference/android/databinding/InverseBindingAdapter.html) The default event will be "android:textAttrChanged" and if you want to have custom two-way bind inversebind, you need to use the attribute with suffix "AttrChanged"

事件的默认值是后缀为的属性名称 "AttrChanged".在上面的示例中,默认值为 android:textAttrChanged,即使未提供.

The default value for event is the attribute name suffixed with "AttrChanged". In the above example, the default value would have been android:textAttrChanged even if it wasn't provided.

最后,在您的活动和string.xml中

Finally, in your activity and your string.xml

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding lBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_main, null, false);
    mViewModel = new ViewModel();
    mViewModel.getText().set("Wednesday");
    lBinding.setViewModel(mViewModel);
    lBinding.setHandler(new Handler());
    setContentView(lBinding.getRoot());
}

string.xml

string.xml

<array name="days">
    <item name="Mon">Monday</item>
    <item name="Tue">Tuesday</item>
    <item name="Wed">Wednesday</item>
</array>

运行代码时,它将显示星期三"作为微调框的默认值.希望这对很多人有帮助

When you run the code, it will show "Wednesday" as the default value for the spinner. Hope this can help for many people

这篇关于使用XML的Android Spinner数据绑定并显示选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆