Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimise Kotlin code for button clicked state

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading