Android databinding with multiple layouts

眉间皱痕 提交于 2020-02-23 06:12:49

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/42536636/android-databinding-with-multiple-layouts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!