【问题标题】:Binding observable field to dynamically created view将可观察字段绑定到动态创建的视图
【发布时间】:2019-11-26 12:20:38
【问题描述】:

我有一个有趣的问题。 在我的代码中,我动态创建了一些 RadioButtons 并将其添加到 RadioGroup。但我无法理解如何使用 mvvm 和数据绑定但不使用 xml 以编程方式向每个 RadioButtons 添加可观察的布尔值... 因此,例如,如果我们在 xml 静态中有 RadioButtons,我们就会有类似的东西:

<RadioButton
       android:id="@+id/someRadioButton"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:checked="@{viewModel.isChecked}"
       android:text="@string/some_string" />

ObservableBoolean isChecked = new ObservableBoolean(false);

在我们的代码中。 但是,如果我们在 xml 中没有按钮但在代码中添加它,我们如何添加 observable 字段呢?喜欢

RadioButton radioButton = new RadioButton(this)
radioButton.text = localeLanguage.languageName
RadioGroup.LayoutParams params = RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.MATCH_PARENT)
radioButton.layoutParams = params
return radioButton

【问题讨论】:

    标签: android mvvm observable android-databinding


    【解决方案1】:

    您可以使用如下所示的 LiveData:

    ViewModel {
      val _radioCheckedLiveData = MutableLiveData<Boolean>()
      val radioCheckedLiveData: LiveData<Boolean> = _radioCheckedLiveData
    
      private fun setRadioChecked(checked: Boolean) = _radioCheckedLiveData.value = checked  
    
      // handle radio check event 
      fun radioChecked(checked: Boolean) {
      if (checked) {
       // do something and change the data source
      }
    
     fun xxxFun() {
       // if you want to change radioButton check status by code, no need to set RadioButton's status directly
       setRadioChecked(true)
     }
    }
    

    }

    Activity {
      val radioButton = RadioButton(context)
      viewModel.radioCheckedLiveData.observe(this) {checked->
         radioButton.checked = checked == true
      }
      radioButton.setOnCheckedListener {checked->
         viewModel.radioChecked(checked)
      }
    }
    

    【讨论】:

      【解决方案2】:

      official doc。你通过xxxBinding = DataBindingUtil.inflate(layoutInflater, R.layout.xxx, viewGroup, false); 得到xxxBinding,然后是xxxBinding.checked = isCheked

      【讨论】:

      • 好的,但是它只连接我们已经在 xml 中创建的视图,但是如果我们在 xml 中没有视图并动态创建它怎么办。答案已更新为更清晰。
      • 您可以使用 LiveData。
      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多