I'm trying to migrate from kotlin synthetics to the recommended view binding pattern. To reduce the boiler code I choosed to use the delegate approach from here.
Now I'm facing a problem, where I don't know how to solve it in an elegant way. I have two similar layouts which differentiate just from several views. For example, let's say layout_a
and layout_b
.
<!-- This is just an example (layout_a) ! -->
<LinearLayout>
<TextView
android:id="@+id/commonView1"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView
android:id="@+id/commonView2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<!-- This is just an example (layout_b) ! -->
<LinearLayout>
<TextView
android:id="@+id/commonView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/commonView2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/specialView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Since I don't want to code the text setter logic for these TextViews
twice in my app, I created an extra singleton class that exactly maps these common views through a view
object. Thanks to kotlin synthetics I was able to reference these views when I used the same id's (like commonView1
and commonView2
). Since now I have to use the binding objects (LayoutABinding and LayoutBBinding in this case) I can't to this.
Sure, I could just change the visibility of the specialView1
programmatically and merge these two layouts in one, but the reason for this duplication was performance and memory efficiency. Of course the above is just an example and in my original app I have a lot more views that would be rendered unnecessarily and waste memory space.
A possible workaround could be to use findViewById in these special cases, which is a bit meh imo.
Is there any way to abstract these bindings?
from Code duplication due to view binding migration
No comments:
Post a Comment