Home > Software engineering >  Optimise Kotlin code for button clicked state
Optimise Kotlin code for button clicked state

Time:08-04

I want to change the button background when the button clicked, the function is work by using this code

bank1.setOnClickListener {
            bank1.setBackgroundResource(R.drawable.selected_btn_border_blue_bg);
            bank2.setBackgroundResource(R.drawable.default_option_border_bg);
            bank3.setBackgroundResource(R.drawable.default_option_border_bg);
            bank4.setBackgroundResource(R.drawable.default_option_border_bg);
        }
        bank2.setOnClickListener {
            bank2.setBackgroundResource(R.drawable.selected_btn_border_blue_bg);
            bank1.setBackgroundResource(R.drawable.default_option_border_bg);
            bank3.setBackgroundResource(R.drawable.default_option_border_bg);
            bank4.setBackgroundResource(R.drawable.default_option_border_bg);
        }
        bank3.setOnClickListener {
            bank3.setBackgroundResource(R.drawable.selected_btn_border_blue_bg);
            bank2.setBackgroundResource(R.drawable.default_option_border_bg);
            bank1.setBackgroundResource(R.drawable.default_option_border_bg);
            bank4.setBackgroundResource(R.drawable.default_option_border_bg);
        }
        bank4.setOnClickListener {
            bank4.setBackgroundResource(R.drawable.selected_btn_border_blue_bg);
            bank2.setBackgroundResource(R.drawable.default_option_border_bg);
            bank3.setBackgroundResource(R.drawable.default_option_border_bg);
            bank1.setBackgroundResource(R.drawable.default_option_border_bg);
        }

But it kinda hardcoded, and make it to so many lines, any way to make the code shorter?

CodePudding user response:

I would keep a variable that keeps track of the selected one like

private var selectedBank: View? = null

And then do

arrayOf(bank1, bank2, bank3, bank4).forEach {
    it.setOnClickListener {
        selectedBank?.setBackgroundResource(R.drawable.default_option_border_bg)
        selectedBank = it
        it.setBackgroundResource(R.drawable.selected_btn_border_blue_bg)
    }
}

you only need to deselected the previous selected one

  • Related