androidandroid-viewbindingandroid-viewbinder

Android view binding for alternate layout


In one project I was working, has 2 layouts for a custom view. For 220 screenWidthDp has different layout. View ids are same in both layouts. Currently layouts are loaded like this

Configuration config = getResources().getConfiguration();
if ( config.screenWidthDp == 220 ) {
   // load layout dashboard_view_220.xml
} else {
   // load layout dashboard_view.xml
}

I want to apply view binding here. The problem is as I have 2 layouts with different name so 2 binding class is generated. So, I have to use if else condition like below

if(config.screenWidthDp == 220) {
    dashboardViewBinding220.title.text = ..
} else {
    dashboardViewBinding.title.text = ..
}

Is there any way I can avoid this condition or any good approach for my current scenario.

Thanks in advance.


Solution

  • Don't do any of this. You would never use a special layout for a specific dp size in Android. You break things into buckets and would use specific layouts for size ranges. And when you do that, you use the built in functionality of the resource system like swXXX, wXXX, etc and give both files the same name in size specific directories. The OS will then automatically pick the right one. If you ever find yourself deciding on what layout to inflate in code, you're doing it wrong.

    See https://developer.android.com/guide/topics/resources/providing-resources#AlternativeResources for the list of qualifiers and what they mean.