如何使用观察者使用当前项目在ViewPager中的位置值来验证EditText中的值?

时间:2019-01-14 08:29:48

标签: android viewmodel android-livedata

我正在使用ViewModel和Livedata。我尝试使用以下代码获取ViewPager在ViewModel中的当前位置

   <android.support.v4.view.ViewPager
            android:id="@+id/moveFromPlansViewPager"
            android:layout_width="0dp"
            android:layout_height="72dp"
            android:layout_marginTop="16dp"
            android:clipToPadding="false"
            android:selectedItemPosition="@={ viewModel.selectedPos }"
            android:paddingStart="16dp"
            android:paddingEnd="16dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/moveFromHeaderTextView" />

我拥有的ViewModel内部

var selectedPos: MutableLiveData<Int> = MutableLiveData()

然后在选定位置找到该值,并将其与EditText中的值进行比较。我以某种方式认为这种逻辑是正确的。但是问题是

 android:selectedItemPosition="@={ viewModel.selectedPos }"

当我将此行添加到布局中时,会导致数据绑定错误。

  

e:[kapt]发生异常:android.databinding.tool.util.LoggedErrorException:发现了数据绑定错误。

有人可以帮助我吗???

1 个答案:

答案 0 :(得分:2)

深入研究错误,它显示出类似以下内容:

****/ data binding error ****msg:Cannot find the getter for attribute 'android:selectedItemPosition' with value type java.lang.Integer on android.support.v4.view.ViewPager ****\ data binding error ****

实际上,这意味着该特定属性不能即装即用绑定(也不能像android:selectedItemPosition="2"这样使用它,例如f.ex。)

有两种选择

  • 您可以添加binding adapter。 F.ex. here,有前途的人
  • 以老式的方式进行:在片段中有MutableLiveData的{​​{1}}的观察者,然后只需手动在那里进行更新:

    selectedPos

第一个更高级,第二个更容易启动和运行。因此,取决于您。