0

In an android app I want to let the user check a radio button and depending on what the user checked I want it to change things in the next activity (e.g. hiding a button or change the text of a button). How am I doing this?

I already found out how to let it change a textview in the next activity, but probably there is a better way for it too.

val rg1 = findViewById<RadioGroup>(R.id.rg1)
val rb1 = findViewById<RadioButton>(R.id.rb1)
val rb2 = findViewById<RadioButton>(R.id.rb2)
val tv1 = findViewById<TextView>(R.id.tv1)
val btnNext = findViewById<Button>(R.id.btnNext)

rg1.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { _, i ->
            when (i) {
                R.id.rb1 -> tv1.text = "something"
                R.id.rb2 -> tv1.text = "something else"
            }
        })

btnNext.setOnClickListener {
                    val result = tv1.text.toString()
                    val intent = Intent(this, Activity2::class.java)
                    intent.putExtra("Result", result)
                    startActivity(intent)
                }

tv1.isGone = true

After doing this in Activity2:

val result = intent.getStringExtra("Result")
val tv2 = findViewById<TextView>(R.id.tv2)
tv2.text = result

it changes tv2 in Activity2 (tv1 is only there to get the text string and shouldn't be displayed in first activity, as I said before, there is probably a better solution too). But most important what to do when I want to hide a button or do something else in the next activity depending on radio buttons?

Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132

1 Answers1

0

not sure if this is an answer to your question or not, but consider this:

you can change

rg1.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { _, i ->
            when (i) {
                R.id.rb1 -> tv1.text = "something"
                R.id.rb2 -> tv1.text = "something else"
            }
        })

to something like this

rg1.setOnCheckedChangeListener(RadioGroup.OnCheckedChangeListener { _, i ->
            when (i) {
                R.id.rb1 -> OneSetupOfYourUI()
                R.id.rb2 -> AnotherSetupOfYourUI()
            }
        })

then define what you want to change inside functions and call those functions, instead of changing every single component.

fun OneSetupOfYourUI(){
//change stuff in here
}

Maybe this helps ?

Then when you start the new activity :

val result = tv1.text.toString()
val intent = Intent(this, Activity2::class.java)
intent.putExtra("Result", result)
startActivity(intent)

Consider adding several intent.putExtra() statements based off of your configured UI or what the user selected

Edit

Just for anyone interested or unsure, you can also simply do this in a when statement:

when (i) {
    R.id.rb1 -> {
    tv1.text = "something"
    etc.
    //now you can do several statements here :)
    }
 }
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51