Android数据绑定具有多种布局 [英] Android databinding with multiple layouts

查看:135
本文介绍了Android数据绑定具有多种布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的android数据绑定有问题.我有不同配置的布局,例如:activity_main.xml/land/activity_main.xml等. 当前,当我使用setContentView方法时,只需传递布局名称,它会自动检测应该选择哪个布局来设置内容视图.

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.

但是,如果我使用数据绑定,那将是解决方案. 据我所知,绑定的名称将根据配置而有所不同.因此,如果我使用ActivityMainBinding,则始终是同一布局的数据绑定.我了解了有关指定标记(每个配置都为bool)并使用if/else语句,然后膨胀所需的绑定的解决方案,但这是很糟糕的解决方案.

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.

对于活动/碎片针对不同配置的布局/端口/sw600端口/土地等使用不同布局的情况,谁能提出更好的解决方案.

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

谢谢!

推荐答案

您可以按照相同的方式使用它:

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
}

所生成的ActivityMainBinding类将是所有匹配布局的绑定的基类,并且将具有所有变量/字段的集合.如果视图"仅在某些布局中,则某些字段引用在某些配置中将为null,因此您必须注意这一点.如果您主要使用数据绑定表达式来设置值或附加事件处理程序,则甚至不需要使用视图"字段引用,因此不必担心.

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.

您始终可以通过在build文件夹中查看生成的代码.您可能会发现有趣的是如何实现它的.

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.

这篇关于Android数据绑定具有多种布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆