1

I am using the ViewModel and Livedata. I tried getting the current position of ViewPager in ViewModel by using the following code

   <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" />

Inside ViewModel I have

var selectedPos: MutableLiveData<Int> = MutableLiveData()

And I find the value in selected position and compare it with the value in EditText. Somehow I think this logic is correct. But the problem is while

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

When I add this line to the layout it causes databinding error.

e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found databinding errors.

Can anybody help me???

Md. Zakir Hossain
  • 1,082
  • 11
  • 24

1 Answers1

2

Diving deeper into an error, it shows something like:

****/ 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 ****

Practically it means that this particular attribute can't be binded out of the box (nor you can not use it like this android:selectedItemPosition="2", f.ex.)

There're couple of alternatives

  • You can add a binding adapter. F.ex. here, there's a promising one
  • Do it in old-school way: have an observer for the MutableLiveData's selectedPos in the fragment and then just do the update there manually:

    viewModel.selectedPos.observe(this, Observer { position ->
            position?.let { moveToSavingsPlansViewPager.setCurrentItem(it, true) }
        })
    

First one is more advanced, the second one is easier to get up-and-running. So it's up to you.

Konstantin Loginov
  • 15,802
  • 5
  • 58
  • 95