Home > front end >  I added [viewbinding] but I can't find my [Button's id from xml file
I added [viewbinding] but I can't find my [Button's id from xml file

Time:03-16

I just can't get id from layout folder: for more explain ; in the code bellow that is in .kt file the radio_group is my id that is all red in code bellow :

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Get radio group selected item using on checked change listener
    radio_group.setOnCheckedChangeListener(
        RadioGroup.OnCheckedChangeListener { group, checkedId ->
            val radio: RadioButton = findViewById(checkedId)
            Toast.makeText(applicationContext," On checked change :" 
                    " ${radio.text}",
                Toast.LENGTH_SHORT).show()
        })
    // Get radio group selected status and text using button click event
    button.setOnClickListener{
        // Get the checked radio button id from radio group
        var id: Int = radio_group.checkedRadioButtonId
        if (id!=-1){ // If any radio button checked from radio group
            // Get the instance of radio button using id
            val radio:RadioButton = findViewById(id)
            Toast.makeText(applicationContext,"On button click :"  
                    " ${radio.text}",
                Toast.LENGTH_SHORT).show()
        }else{
            // If no radio button checked in this radio group
            Toast.makeText(applicationContext,"On button click :"  
                    " nothing selected",
                Toast.LENGTH_SHORT).show()
        }
    }
}
// Get the selected radio button text using radio button on click listener
fun radio_button_click(view: View){
    // Get the clicked radio button instance
    val radio: RadioButton = findViewById(radio_group.checkedRadioButtonId)
    Toast.makeText(applicationContext,"On click : ${radio.text}",
        Toast.LENGTH_SHORT).show()
}

} the radio_group is all red error and cant find the solution for that after build again and ctrl enter please help if there is better way...

CodePudding user response:

This is not how you use view binding. The code you wrote is how you would do it with Kotlin synthetics, which is deprecated now. Enabling viewBinding requires more work than simply enabling it. I suggest reading the documentation here about how to do it:

Migrate from Kotlin synthetics to Jetpack view binding

  • Related