I am using one model for 2 fragments. First one is displaying countryName and countryCode, Second one is selecting country. When i select country i set a new value models field and going back to first fragment EditText is also setting empty text to models fields, thats why two way data binding is not working. If i change EditText to TextView, all is working fine.
Model:
public final ObservableField<String> countryName = new ObservableField<>();
public final ObservableField<String> countryCode = new ObservableField<>();
public void onCountrySelected(CountryEnum countryEnum) {
countryName.set(countryEnum.getName());
countryCode.set(countryEnum.getCode());
getNavigator().onGoBack();
}
XML:
<EditText
android:id="@+id/countryNameTextView"
android:layout_width="match_parent"
android:layout_height="@dimen/_56dp"
android:layout_margin="8dp"
android:drawableEnd="@drawable/ic_arrow_drop_down"
android:drawableRight="@drawable/ic_arrow_drop_down"
android:hint="@string/country_code"
android:textColorHint="@color/black"
android:singleLine="true"
android:focusable="false"
android:gravity="center_vertical"
android:onClick="@{()->viewModel.onCountryClick()}"
android:text="@={viewModel.countryName}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/appBarLayout"/>
<EditText
android:id="@+id/codeEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="@dimen/_48dp"
android:layout_marginTop="16dp"
android:text="@={viewModel.countryCode}"
android:singleLine="true"
android:gravity="center_vertical"
tools:text="+998"
app:layout_constraintStart_toStartOf="@+id/countryNameTextView"
app:layout_constraintTop_toBottomOf="@+id/countryNameTextView"/>
Edit:

Country Enum:
public enum CountryEnum {
Country_1("Afghanistan", "Афганистан", "93", "--- --- ---"),
Country_2("Albania", "Албания", "355", "-- --- ----"),
Country_3("Algeria", "Алжир", "213", "--- -- -- --"),
Country_4("American Samoa", "Американское Самоа", "1684", "--- ----"),
Country_5("Andorra", "Андорра", "376", "-- -- --"),
Country_6("Angola", "Ангола", "244", "--- --- ---"),
Country_7("Anguilla", "Ангуилла", "1264", "--- ----"),
}
For fragment, try to set lifecycleOwner
Simple example (Kotlin):
class FragmentMain : Fragment() {
private lateinit var viewDataBinding: MainFragmentBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewDataBinding = DataBindingUtil.inflate(
inflater,
R.layout.main_fragment_profile,
container,
false
)
viewDataBinding.lifecycleOwner = this
return viewDataBinding.root
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With