[英]Android two way databinding is not working for edittext in Fragment
我正在使用一個模型處理2個片段。 第一個是顯示countryName和countryCode,第二個是選擇國家。 當我選擇國家/地區時,我設置了一個新的值模型字段,然后回到第一個片段,EditText也在模型字段中設置了空文本,這就是為什么雙向數據綁定不起作用的原因。 如果我將EditText更改為TextView,則一切正常。
模型:
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"/>
國家枚舉:
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", "--- ----"),
}
對於片段,請嘗試設置lifecycleOwner
簡單示例(科特琳):
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.