Optimizing code structure for ViewHolder members - Kotlin

26 Views Asked by At

I have a ViewHolder that looks something like this:

class ViewHolder(
        itemView: View,
        var mSettingsRadioButton: RadioButton = itemView.findViewById(...),
        var mSettingsCheckBox: CheckBox = itemView.findViewById(...),
        var mSettingsChevron: Icon = itemView.findViewById(...)
    ) : RecyclerView.ViewHolder(itemView)

The idea is to make the the other two invisible when one of them is active, i.e. if a checkbox is active, the chevron and radio button should be invisible.

Right now I am using 3 functions for this purpose something like this:

fun setCheckbox(viewHolder: ViewHolder) {
        viewHolder.apply {
            mSettingsChevron.visibility = GONE
            mSettingsRadioButton.visibility = GONE
            mSettingsCheckBox.let {
                it.visibility = VISIBLE
                it.isChecked = false
            }
        }
    }

Although this approach works, I have 3 functions that are practically doing the same thing. I am looking for much cleaner and optimized way of writing this functionality. Any suggestion is much appreciated. Thanks!!

1

There are 1 best solutions below

2
Vojin Purić On

If you want to use only one function you could, and it would remove redundant code so you would be achieving DRY principle.

fun setVisibility(isCheckBoxVisible: Boolean, isRadioButtonVisible: Boolean, isChevronVisible: Boolean) {
    mSettingsCheckBox.visibility = if (isCheckBoxVisible) View.VISIBLE else View.GONE
    mSettingsRadioButton.visibility = if (isRadioButtonVisible) View.VISIBLE else View.GONE
    mSettingsChevron.visibility = if (isChevronVisible) View.VISIBLE else View.GONE
}

And now you would just call setVisibility accordingly

// Show only the checkbox
viewHolder.setVisibility(true, false, false)

// Show only the radio button
viewHolder.setVisibility(false, true, false)

// Show only the chevron
viewHolder.setVisibility(false, false, true)

// And if you need
// Hide all views
viewHolder.setVisibility(false, false, false)