Android两种方式的数据绑定不适用于Fragment中的edittext

时间:2018-08-01 06:01:37

标签: android mvvm android-databinding android-viewmodel

我正在使用一个模型处理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"/>

编辑: enter image description here

国家/地区枚举:

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", "--- ----"),
}

1 个答案:

答案 0 :(得分:0)

对于片段,请尝试设置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
}
}