Home > database >  Alternative to findviewbyid to find button
Alternative to findviewbyid to find button

Time:04-09

I have 26 buttons which all have an id like button_0 button_1 etc.

I've saw that findviewbyid is deprecated and I don't want to have to call all those 26 button line by line. So my first idea was to make an array of them, but there is still the same problem I need to write them all at least one time. I didn't find a way to achieve that with view binding or by calling the button with a string and need help. Thanks!

CodePudding user response:

  1. Wrap your buttons inside ViewGroup (constraintLayout, LinearLayout, etc), give it an Id
  2. call findViewById to the ViewGroup , not the button
  3. get ViewGroup children by using children method
// just an example
val buttonContainer = findviewbyid<LinearLayout>()
val buttons = buttonContainer.children //return Sequence<View>

buttons.forEach { btn ->
  if(btn is Button){
    // do something
  } 
}

CodePudding user response:

In the app level build.gradle file, just add viewBinding.

buildFeatures {
    viewBinding true
}

In your activity create a variable for the binding of your activity layout. The binding will be camel notation in reverse.

lateinit var bindingActivity: ActivityMainBinding

Then add this to the onCreate() method.

bindingActivity = ActivityMainBinding.inflate(layoutInflater)
    setContentView(bindingActivity.root)

After you have that in place, you can access your views by just writing binding.viewId and it’s the equivalent of you using find view by id. If you want to access more than one view at the same time using Kotlin just use apply.

// access single view
val text = binding.textTitle.text

// access multiple views without calling binding each time
binding.apply {
textTitle.text = “hello”
val data = inputText.text.toString()
}
  • Related