Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android databinding with multiple layouts

I have issues with the android data binding. I have layouts for different configurations like ie: activity_main.xml / land/activity_main.xml etc. Currently when I use setContentView method, just pass the layout name, and it automatically detects which of the layouts should choose to set content view.

But If I use the data binding what would be the solution for that. As I know the names for the binding would be different depending onto the configuration. So If I use ActivityMainBinding, that always will be the data binding for the same layout. I read about the solution to specify markers( bools for each config) and use the if/else statements and then to inflate the needed binding but that is so bad solution.

Can anyone suggest better solution for the case that an activity/fragment uses different layout for different configurations layout/port/ sw600-port/land etc.

Thanks!

like image 485
sromanov Avatar asked Feb 04 '23 23:02

sromanov


1 Answers

You can just use it the same way:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(this,
        R.layout.activity_main);
    // set all variables in binding
}

The ActivityMainBinding class that is generated will be a base class for bindings of all matching layouts and will have the aggregate of all variables/fields. If Views are only in some of the layouts, some of the field references will be null in some configurations, so you'll have to watch for that. If you are using mostly data binding expressions to set values or attach event handlers, you won't even need to use the View field references, so you won't have to worry about that.

If Views have different types in different layouts, the common base class will be used for the View field.

You can always look at the generated code by looking in the build folder. You might find it interesting to see how it is implemented.

like image 136
George Mount Avatar answered Feb 07 '23 13:02

George Mount