kotlin- change decimal places on multiple fragments from one fragment

Viewed 41

for my app i read in multiple values from Bluetooth connected sensors. One fragment allows you to edit the sensors and another fragment shows all values in a tableView. On a third settings fragment, i want to be able to change the decimal places the values on all fragments appear.

i know to change the decimal format i use the following code.

 var form = DecimalFormat("#,###.##") // number format

and to add this format to the values do the following

form.format(temperature)

currently i have a radio group, with each radio button set to change the how many decimal places in the variable form.

how do i make this change appear across all fragments not just the setting fragments? will i need a shared view model?

1 Answers

Shared ViewModel is good fit for this problem, simply create a ViewModel with form property and in every fragment get an instance of ViewModel associated with activity as

private val viewModel: SharedViewModel by activityViewModels()

Now you can update the form property on radio change as

radioGroup.setOnCheckedChangeListener { group, checkedId ->
    val format = when(checkedId){
        R.id.radio_two ->   TWO_DECIMAL_PLACES
        R.id.radio_three -> THREE_DECIMAL_PLACES
        else -> DEFAULT_FORMAT
     }
     viewModel.form = DecimalFormat(format)
}

After this simply use value of this property before showing data

Related