How to replace findViewById(v.getId()) with View Binding?

Issue

By clicking on a button, I can find the id of the button through findViewById(v.getId()). How can I replace it with View Binding?

This is my code:

fun TastoClick(v: View) {
    val btn = findViewById(v.getId()) as Button
    var name = btn.text.toString().toInt()
}

Solution

Please do give the documentation for View Binding a look I’m sure you will find it answers your question.

But in summary:

  1. in the module-level build.gradle add:

    android {
        ...
        buildFeatures {
            viewBinding true
        }
    }
    
  2. For a Fragment with an xml like result_profile.xml a binding class will be generated in the format: ResultProfileBinding you will then need to setup an instance for that class as below:

result_profile.xml:

<LinearLayout ... >
    <TextView android:id="@+id/name" />
    <ImageView android:cropToPadding="true" />
    <Button android:id="@+id/button"
        android:background="@drawable/rounded_button" />
</LinearLayout>

ResultProfileFragment.kt:

private var _binding: ResultProfileBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = ResultProfileBinding.inflate(inflater, container, false)
    val view = binding.root
    return view
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
  1. For an Activity:

ResultProfileActivity.kt:

private lateinit var binding: ResultProfileBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ResultProfileBinding.inflate(layoutInflater)
    val view = binding.root
    setContentView(view)
}

You can then access the layout elements like this:

binding.name.text = viewModel.name
binding.button.setOnClickListener { viewModel.userClicked() }

Update:

If you have one listener for multiple buttons you can simple compare the view passed into the onClick method with your view bindings id i.e.

v.id == binding.yourbutton.id

A switch statement or if statement may be used to check which id matches the view that was clicked.

Answered By – David Kroukamp

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published