android视图模型可变数据不更新,双向数据绑定



我有这样的片段:


class LoginFragment : Fragment() {
private lateinit var viewModel: AuthViewModel
private lateinit var mBinding: FragmentLoginBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = DataBindingUtil.inflate<ViewDataBinding>(
inflater, R.layout.fragment_login, container, false
) as FragmentLoginBinding
val view: View = mBinding.root
viewModel = ViewModelProvider(requireActivity()).get(AuthViewModel::class.java)
mBinding.login?.invoke(viewModel)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initLoginButton()
}
fun initLoginButton() {
mBinding.btLogin.setOnClickListener {
Log.d("d--login", "login clicked")
Log.d("d--login", viewModel.username.value)
Log.d("d--login", viewModel.password.value)
}
}
}

我的AuthViewModel如下所示:

class AuthViewModel : ViewModel() {
operator fun invoke(viewModel: AuthViewModel) {}
val username = MutableLiveData<String>("")
val password = MutableLiveData<String>("")
val passwordRe = MutableLiveData<String>("")
}

在XML中,我有两个编辑文本:

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusedByDefault="true"
android:inputType="text"
android:text="@={login.username}"
android:textColor="@color/colorWhite" />

但是用户名没有在viewmodel上更新,我也尝试过ObservableField。同样的问题。

在家长活动中,我有:


mBinding = DataBindingUtil.setContentView(this, R.layout.activity_authentication)
viewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
mBinding.auth?.invoke(viewModel)
mBinding.lifecycleOwner = this

您的ViewModelFragment没有任何连接

这样做:

片段:

private lateinit var vm: AuthViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)    
vm = activity?.run {
ViewModelProviders.of(this)[AuthViewModel::class.java]
} ?: throw Exception("Invalid Activity")       
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentLoginBinding = DataBindingUtil.inflate(inflater,
R.layout.fragment_login, container, false)
binding.viewmodel = vm//attach your viewModel to xml
return binding.root
}
}

相关内容

  • 没有找到相关文章

最新更新