我想用片段绑定数据,并像活动一样进行绑定,但它显示了错误。这表明val无法重新分配,我将val更改为var,但仍然存在相同的问题,但为什么?
这是我的fragment_登录布局
<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="login"
type="com.binod.rojgar.viewmodel.AuthViewModel" />
</data>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.auth.Login">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_gravity="center"
android:layout_height="match_parent">
...
这是我的登录类
class Login : Fragment(),AuthListner {
private lateinit var binding: FragmentLoginBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate<FragmentLoginBinding>(inflater,
R.layout.fragment_login, container, false)
val viewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
binding.login = viewModel //this line shows error showing val cant be reassigned and i make var but still it shows same error
viewModel.authListner=this
return binding.root
}
}
这是我的authviewmodel
class AuthViewModel:ViewModel(){
var name:String?=null
var phoneNum:String?=null
var password:String?=null
var comform_password:String?=null
var authListner:AuthListner?=null
fun loginButton(view:View)
{
authListner?.onStart()
if (phoneNum.isNullOrEmpty() || password.isNullOrEmpty())
{
authListner?.onFailure("Invalid phone num or password")
}
authListner?.onSuccess()
}
}
2条答案
按热度按时间5vf7fwbs1#
试试这个:
mctunoxg2#
你可以尝试下面的方法