我的视图模型数据未绑定到edittext

问题描述 投票:0回答:1

我已经将一个视图模型绑定到一个活动,并且运行良好,但是在另一个我绑定了视图模型的活动中,它没有显示任何数据。这是我的活动中的viewmodel变量声明:

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    >
    <data>
        <variable name="profileViewModel"
            type="com.kreeti.gogal.ui.profile.ProfileViewModel"
            />
    </data>
   ......
   <EditText
       style="@style/convertible_edit_text"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:drawableEnd="@drawable/ic_edit"
       android:text="@={profileViewModel.firstName}"/>

这是我的视图模型:

class ProfileViewModel constructor(
    val repository: ProfileRepository,
    private val mContext: Context
) : ViewModel() {
    var firstName: String? = null
    ....
init {
      Coroutines.main {
           try {
               repository.getProfileDetails().let {
                   firstName = it.data.first_name  // Here I am fetching the data
                }
           ....
     }
}

这是我的活动课程

class EditProfile : AppCompatActivity(), ResponseListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val networkConnectionInterceptor = NetworkConnectionInterceptor(this)
        val api = BaseApi.invoke(networkConnectionInterceptor, AuthorizedApi::class.java)
        val profileRepository = ProfileRepository(api)
        val factory = ProfileViewModelFactory(profileRepository, this)
        val viewModel = ViewModelProvider(this, factory).get(ProfileViewModel::class.java)

        val binding: ActivityEditProfileBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_profile)
        binding.profileViewModel = viewModel
     }

我不明白为什么我的edittext无法获取数据

android kotlin android-databinding android-viewmodel
1个回答
0
投票

如果您在xml中使用数据绑定,则应该是:android:text="@{profileViewModel.firstName}"而不是android:text="@={profileViewModel.firstName}",但我认为没有问题。

您也可能对此codelab感兴趣

PS:profileViewModel不应引用context,因为它可能会产生一些错误,如果您确实需要context,则可以使用AndroidViewModel代替ViewModel实现。 AndroidViewModel使您可以访问ApplicationContext。

© www.soinside.com 2019 - 2024. All rights reserved.