Search code examples
javaandroidandroid-viewbinding

return findViewById() in viewbinding


I am trying to optimize old code. And I am trying to replace findviewbyid with viewbinding. But how do I return viewbinding id instead of findviewbyid?

private TextView getTextView(int id){
        return (TextView) findViewById(id);
}

This is the old code. But I want to apply viewbinding. I want it to work something like this. As I have no idea how to do it.

private TextView getTextView(int id){
        return sampleViewBinding(id);
}

How can I achieve this?


Solution

  • The whole point of View Binding is to avoid findViewById() calls. It does it for you automatically. What you are trying to do is treating View Binding like findViewById(). Whenever you need to access any view, all you have to do it call the generated binding class with your id in the camel-case. for e.g main_layout.xml is gonna have a class generated by the name MainLayoutBinding so you are going to access all the view inside your layout by calling the MainLayoutBinding's instance and the id you want to access.