简体   繁体   中英

Why LiveData not updating? (Android, Kotlin)

How to expose MutableLiveData as LiveData?.

Code below not working.

SimpleMixerFragment.kt

private lateinit var binding: MixerSimpleFragmentBinding
private lateinit var viewModel: SimpleMixerViewModel

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    // Inflate view and obtain an instance of the binding class
    binding = DataBindingUtil.inflate(
        inflater,
        R.layout.mixer_simple_fragment,
        container,
        false
    )

    viewModel = ViewModelProvider(this).get(SimpleMixerViewModel::class.java)

    binding.simpleMixerViewModel = viewModel

    binding.lifecycleOwner = viewLifecycleOwner

    return binding.root
}

SimpleMixerViewModel.kt

class SimpleMixerViewModel : ViewModel() {

   private val _etDate = MutableLiveData<String>()
   val etDate: LiveData<String>
       get() = _etDate
}

mixer_simple_fragment.kt

<variable name="simpleMixerViewModel" type="....SimpleMixerViewModel" />

<com.google.android.material.textfield.TextInputEditText
                                android:id="@+id/etDate"                
                                android:text="@{simpleMixerViewModel.etDate}"/>

This works instead.

SimpleMixerViewModel.kt

class SimpleMixerViewModel : ViewModel() {

   val etDate = MutableLiveData<String>()
}

mixer_simple_fragment.xml

<variable name="simpleMixerViewModel" type="....SimpleMixerViewModel" />

<com.google.android.material.textfield.TextInputEditText
                                android:id="@+id/etDate"                
                                android:text="@={simpleMixerViewModel.etDate}"/>

@{} registers a one-way binding, meaning if you modify MutableLiveData from code, then it would propagate the changes to the EditText .

@={} registers a two-way binding, meaning if you modify either the MutableLiveData OR the android:text property, then it will update MutableLiveData -> android:text OR android:text -> MutableLiveData (whichever was modified).

To use two-way binding, you must expose the mutable version of LiveData so that the binding can write the new value of the EditText into the MutableLiveData.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM