How to bind method on RadioGroup on checkChanged event with data-binding

前端 未结 5 1758
甜味超标
甜味超标 2021-01-31 09:32

I was searching over the internet for how to perform the new cool android data-binding over the RadioGroup and I didn\'t find a single blog post about it.

5条回答
  •  半阙折子戏
    2021-01-31 10:09

    In my current project, I did it like this. I have three currency in the project and I choose one of them via RadioGroup.

    It's enum with currencies:

    enum class Currency(val value: Byte) {
        USD(0),
        EUR(1),
        RUB(2);
    
        companion object Create {
            fun from(sourceValue: Byte): Currency = values().first { it.value == sourceValue }
            fun from(sourceValue: String): Currency = values().first { it.toString() == sourceValue }
        }
    }
    

    A piece of my ViewModel:

        class BaseCurrencyViewModel : ViewModelBase() {
            /**
             * Selected currency
             */
            val currency: MutableLiveData = MutableLiveData()
    
            /**
             *
             */
            init {
                currency.value = Currency.USD   // Init value
            }
      }
    

    Part of my layout (pay attention to binding in RadioGroup and tags of RadioButton):

    
    
        
    
        
    
        
    
    

    And the final part - binding adapter.

    @BindingAdapter("selectedCurrency")
    fun setSelectedCurrency(view: View, value: MutableLiveData?) {
        view.getParentActivity()?.let { parentActivity ->
            value?.observe(parentActivity, Observer { value ->
                view.findViewWithTag(value.toString())
                    ?.also {
                        if(!it.isChecked) {
                            it.isChecked = true
                        }
                    }
                }
            )
    
            (view as RadioGroup).setOnCheckedChangeListener { radioGroup, checkedId ->
                val currency = Currency.from(radioGroup.findViewById(checkedId).tag as String)
                if(value != null && value.value != currency) {
                    value.value = currency
                }
            }
        }
    }
    

    In this way, I got two-way binding between RadioGroup and a property in my ViewModel.

提交回复
热议问题