r/android_devs • u/AD-LB • Sep 14 '21
Help Question: suppose in code you get to inflate out of 2 possible layouts, how would you migrate this to view-binding?
Using view-binding, I got to avoid findViewById and also reduced the number of variables and fields that I need to declare.
I work on an old project that in some cases there is a condition that decides which layout to use, and has layouts that in terms of IDs, they either have the exact set of IDs, or a bit different (one has some view with an ID, and in the other it doesn't exist).
When it's just one layout, it's easy to migrate to view-binding, but how can I do it in this case?
1
Upvotes
2
u/Zhuinden EpicPandaForce @ SO Sep 14 '21
This sort of dynamic behavior is what you can use findViewById for
1
u/MKevin3 Sep 14 '21
Is there a reason this is not a different Fragment / Activity? Are there a ton of differences between the two layouts? Seems like maybe if this is an activity you could fire up a different fragment depending on that if statement checking which layout to use.
Or you could do two different Binding objects, one for one layout, one for the other
private var bindingA: FragABinding? = nullprivate var bindingB: FragBBinding? = nullIf (doAStuff) {bindingA = FragABinding.inflate(layoutInflater)} else {bindingB = FragBBinding.inflate(layoutInflater)}You will have to check the
if (doAStuff)in the code or null checks forbindingAandbindingB1
u/narkusv Sep 14 '21
You could use an interface which has two implementations - viewBindingA/viewBindingB and access the correct ViewBinding through that. But I think using findViewById is easier?
1
u/yacovmm Sep 14 '21
Depends how big its that class/case, But I would based on a condition inflate the view through the view Binding.
And try to separate based on which view was inflated. Like if viewA so I would create a method like bindViewAStuff...
Even if maybe I would repeat some code in this way but should be more clean.
Or even better I would separate in two activities/fragments and navigate to each one conditionally instead of inflate conditionally...
Sometime the Dont repeat yourself principle is had practice when we think about clean code.
1
u/[deleted] Sep 14 '21
Forget that it's ViewBinding, your question simply becomes "How do I declare and initialize a variable/type based on a condition?" Treat it that way and it becomes a simpler programming problem that you can solve.