7

I'm trying to use android two-way databinding with checkBox in a fragment.
I have multiple fragments in viewPager with custom FragmentStatePagerAdapter and one viewModel in first fragment.
I have a checkbox with the code below:

<CheckBox
            android:id="@+id/checkbox_accept_rules"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="@={viewmodel.isAccept}"
            android:gravity="right"
            android:text="text..." />

In viewModel:

private final ObservableBoolean isAccept = new ObservableBoolean(false);

When I go to last fragment and return to first one the checkBox is not checked anymore, the color of the checkbox is true but the check icon is not there! Had anyone this problem before?

Thanks in advance

Dr.jacky
  • 3,341
  • 6
  • 53
  • 91
Sepehr Nozaryian
  • 370
  • 4
  • 15

1 Answers1

0

View pager's fragment has an unique lifecycle than usual fragment.If you have three fragments A->B->C and you swipe B from C then fragment A will be destroyed.You can check it by override a method onDestroy in Fragment A.When you again swipe to A it will recreate again,and all the value will initialize again.That is the reason your checkbox's value is unchecked.Try to save checkbox's value in sharedPreference,so whenever it will recreate it will take the value's from sharedPreference and remeber to clear the sharedPrefence value when your viewpager will be destroyed or it'scontainer activity destroyed.

Saddan
  • 1,546
  • 16
  • 19