0

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?

2 Answers2

0

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.

Somesh Kumar
  • 8,088
  • 4
  • 33
  • 49
0

If your layout file name is fragment_dashboard.xml and has within a textview with an Id userNameTvId, then you normally do this without using data binding:

val view = inflater.inflate(R.layout.fragment_dashboard, container, false)
val textview = view.findViewById(R.id.userNameTvId)

but with viewBinding it is done by chaining. this textview is acceptable through the binding object. The above will be rewritten like this using viewBinding:

val binding = FragmentDashboardBinding.inflate(inflater)
binding.userNameTvId

// to pass a value you can just do
binding.userNameTvId = "SomeOne"

val view = binding.root
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
SomeOne
  • 31
  • 2