如何在kotlin中使用带片段的数据绑定?

l0oc07j2  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(268)

我想用片段绑定数据,并像活动一样进行绑定,但它显示了错误。这表明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()
    }

  }
5vf7fwbs

5vf7fwbs1#

试试这个:

binding = FragmentLoginBinding.inflate(inflater, container, false)
mctunoxg

mctunoxg2#

你可以尝试下面的方法

var viewDataBinding: T? = null
    private var mViewModel: V? = null
    abstract val bindingVariable: Int

   override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        viewDataBinding = DataBindingUtil.inflate(inflater, layoutId, container, false)
        return viewDataBinding!!.root
    }

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewDataBinding!!.setVariable(bindingVariable, mViewModel)
        viewDataBinding!!.executePendingBindings()
    }

相关问题