[英]Android spinner data binding with xml layout
I'm using DataBinding class to bind data from the model to the UI elements.我正在使用 DataBinding 类将数据从模型绑定到 UI 元素。 I could get the binding working for an EditText using
android:text="@{data.testData}"
.我可以使用
android:text="@{data.testData}"
为 EditText 绑定工作。 This somehow doesn't work for a Spinner.这在某种程度上不适用于 Spinner。 Any ideas or solutions to get the data from the
Pojo
class and display it on a spinner (I have 45 spinners)从
Pojo
类获取数据并将其显示在微调器上的任何想法或解决方案(我有 45 个微调器)
Here is an example, that I used to do it:这是一个例子,我曾经这样做过:
First, your layout xml (example my_layout.xml
):首先,您的布局 xml(例如
my_layout.xml
):
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="spinnerAdapter"
type="android.widget.ArrayAdapter" />
</data>
...
<android.support.v7.widget.AppCompatSpinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:adapter="@{spinnerAdapter}" />
....
</layout>
Then your java code ( MyLayoutBinding mBinding
):然后你的 java 代码(
MyLayoutBinding mBinding
):
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, mData);
mBinding.setSpinnerAdapter(adapter);
My solution: XML:我的解决方案:XML:
<androidx.appcompat.widget.AppCompatSpinner
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@drawable/button_background"
android:entries="@{viewModel.items}"
android:padding="5dp"
android:selectedItemPosition="@{viewModel.itemPosition}" />
ViewModel:视图模型:
var items: ArrayList<Item> = ArrayList()
var itemPosition = MutableLiveData<Int>()
Activity/Fragment:活动/片段:
viewModel.itemPosition.observe(requireActivity(),
object : Observer<Int> {
override fun onChanged(t: Int?) {
//you will get the position on selection os spinner
//get value by position
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.