博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
android数据绑定_Android数据绑定高级概念
阅读量:2533 次
发布时间:2019-05-11

本文共 9413 字,大约阅读时间需要 31 分钟。

android数据绑定

In this tutorial we’ll look into some other tricky usages of Data Binding in our application. For a better understanding of this tutorial, do view the .

在本教程中,我们将研究应用程序中数据绑定的其他一些棘手用法。 为了更好地理解本教程,请查看 。

Android数据绑定概述 (Android Data Binding Recap)

In the previous tutorial we looked into how Data Binding approach removes the need of using findViewById to hookup the UI view objects in our app code.

Another advantage of Data Binding over findViewById is that it enhances the performance of the application.
Using findViewById requires us to lookup the view in the entire hierarchy every time it’s invoked. Thus it requires a single pass through the entire view hierarchy for every child view. On the other hand, Data Binding uses just one single pass and stores all the field names of every child view layout. There’s no need for a second pass since we’ve already found all the views in the first pass itself.

在上一教程中,我们研究了数据绑定方法如何消除了使用findViewById连接应用程序代码中的UI视图对象的需求。

与findViewById相比,数据绑定的另一个优点是它可以提高应用程序的性能。
使用findViewById要求我们每次在视图中调用整个层次结构。 因此,它需要为每个子视图单次遍历整个视图层次结构。 另一方面,数据绑定仅使用一次传递,并存储每个子视图布局的所有字段名称。 不需要第二遍,因为我们已经在第一遍本身中找到了所有视图。

Android数据绑定概述 (Android Data Binding Overview)

Data Binding has lots more to do than just getting rid of findViewById. You must have experienced scenarios where a ListView or a RecyclerView or just a normal layout for the sake uses a data model to add the relevant information into the layout. Even if we get the field names of the view layouts in our MainActivity it still requires us to write a lot of repetitive code snippets. Let’s say we have a layout where we’re adding data from a DataModel.java class dynamically and updating the values after a specific interval. The following code snippet shows an example implementation of Data Binding when the data is supplied to the layout from a Data Model class.

数据绑定还有很多要做的事情,而不仅仅是摆脱findViewById。 您必须具有经验丰富的场景,其中ListView或RecyclerView或仅出于普通布局而使用数据模型将相关信息添加到布局中。 即使我们在MainActivity中获得了视图布局的字段名称,它仍然需要我们编写很多重复的代码片段。 假设我们有一个布局,其中要动态添加DataModel.java类中的数据,并在特定间隔后更新值。 下面的代码片段显示了将数据从数据模型类提供给布局时数据绑定的示例实现。

activity_main.xml

activity_main.xml

The DataModel.java class is given below.

下面给出了DataModel.java类。

public class DataModel {    String name;    int image;    String summary;    public DataModel(int image, String name, String summary) {        this.name = name;        this.summary = summary;        this.image = image;    }    public int getImage() {        return image;    }    public void setImage(int image) {        this.image = image;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getSummary() {        return summary;    }    public void setSummary(String summary) {        this.summary = summary;    }}

The MainActivity.java is given below.

MainActivity.java在下面给出。

public class MainActivity extends AppCompatActivity {    ActivityMainBinding binding;    Timer timer;    int i = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);        DataModel dataModel = new DataModel(R.drawable.marsh, "Android MarshMallow", "Android 6.0");        binding.imageView.setImageResource(dataModel.getImage());        binding.name.setText(dataModel.getName());        binding.summary.setText(dataModel.getSummary());        timer= new Timer();        timer.scheduleAtFixedRate(new TimerTask() {            @Override            public void run() {                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        if (i == 0) {                            DataModel dataModel = new DataModel(R.drawable.lollipop, "Android Lollipop", "Android 5.0");                            binding.imageView.setImageResource(dataModel.getImage());                            binding.name.setText(dataModel.getName());                            binding.summary.setText(dataModel.getSummary());                            i=1;                        } else {                                                        i=0;                            DataModel dataModel = new DataModel(R.drawable.marsh, "Android MarshMallow", "Android 6.0");                            binding.imageView.setImageResource(dataModel.getImage());                            binding.name.setText(dataModel.getName());                            binding.summary.setText(dataModel.getSummary());                        }                    }                });            }        }, 3000, 3000);     }}

We’ve used a timer that keeps changing the layout data alternately after every 3 seconds.

As you can see there is too much repetitive code for setText and setImageResource.
DataBinding allows us to directly assign the data from the DataModel class inside our xml layout. We’ll see how.

我们使用了一个计时器,该计时器每3秒钟会不断交替更改布局数据。

如您所见,setText和setImageResource的重复代码太多。
DataBinding允许我们直接在xml布局中分配来自DataModel类的数据。 我们将看看如何。

Android数据绑定项目结构 (Android Data Binding Project Structure)

Android数据绑定代码 (Android Data Binding Code)

We define the DataModel class variable object in the xml as shown in the layout below.

我们在xml中定义了DataModel类变量对象,如下图所示。

activity_main.xml

activity_main.xml

DataBinding has its own expression language for layout files. It allows us to assign the data directly in the xml attributes.

DataBinding具有自己的布局文件表达语言。 它允许我们直接在xml属性中分配数据。

  • <data> is put in the layout and serves as as wrapper for variables used in the layout tag can also be used to import types we need in your work example a View type as shown below:
        

    The alias attribute is used to assign the import type a name for convenience.

    <data>放在布局中,用作布局标签中使用的变量的包装,也可以用于导入工作示例中所需的类型View类型,如下所示:

    为了方便起见, alias属性用于为导入类型分配名称。

  • <variable> contains name and type describing the name of the variable and its full name respectively (including the package name)

    <variable>包含名称和类型,分别描述变量的名称及其全名(包括程序包名称)
  • @{} container used for describing the expression. For example, displaying field names or displaying data using expressions and operators(we’ll look at this later)

    @ {}容器,用于描述表达式。 例如,显示字段名称或使用表达式和运算符显示数据(我们将在后面介绍)

The MainActivity.java is given below.

MainActivity.java在下面给出。

public class MainActivity extends AppCompatActivity {    ActivityMainBinding binding;    Timer timer;    int i = 0;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);        DataModel dataModel = new DataModel(R.drawable.marsh, "Android MarshMallow", "Android 6.0");        binding.setData(dataModel);        timer = new Timer();        timer.scheduleAtFixedRate(new TimerTask() {            @Override            public void run() {                runOnUiThread(new Runnable() {                    @Override                    public void run() {                        if (i == 0) {                            DataModel dataModel = new DataModel(R.drawable.lollipop, "Android Lollipop", "Android 5.0");                            binding.setData(dataModel);                            i = 1;                        } else {                            i = 0;                            DataModel dataModel = new DataModel(R.drawable.marsh, "Android MarshMallow", "Android 6.0");                            binding.setData(dataModel);                        }                    }                });            }        }, 3000, 3000); // End of your timer code.    }    @BindingAdapter({"android:src"})    public static void setImageViewResource(ImageView imageView, int resource) {        imageView.setImageResource(resource);    }}

Doesn’t it look a lot cleaner and more readable now!

它现在看起来更干净,更易读了!

Few inferences drawn from the above code:

从以上代码中得出的推论很少:

  • The DataModel object is directly set to binding object as
    binding.setData(dataModel);.
    The method setData is generated from the variable name defined in the xml layout

    将DataModel对象直接设置为绑定对象,如下所示
    binding.setData(dataModel);
    setData方法是从xml布局中定义的变量名生成的
  • ImageView is a source attribute. For the BindingAdapter to recognise the android:src attribute we explicitly define it in the MainActivity.java as
    @BindingAdapter({"android:src"})    public static void setImageViewResource(ImageView imageView, int resource) {        imageView.setImageResource(resource);    }

    ImageView是一个源属性。 为了使BindingAdapter能够识别android:src属性,我们在MainActivity.java中将其显式定义为

Android数据绑定应用程序输出 (Android Data Binding App Output)

The output of the application in action is given below.

实际应用程序的输出如下。

The expression language provided by DataBinding has much more to use than just specifying the data.

We can specify the xml attributes based on certain conditions as shown below.

DataBinding提供的表达语言要使用的不仅仅是指定数据。

我们可以根据某些条件指定xml属性,如下所示。

android:text="@{data.name != null ? data.name : data.summary}"

The above line can be be written in a more compact form:

上面的行可以用更紧凑的形式编写:

android:text="@{data.name ?? data.summary}"

This brings an end to this tutorial. You can download the Android AdvanceDataBinding Project from the below link.

本教程到此结束。 您可以从下面的链接下载Android AdvanceDataBinding项目

翻译自:

android数据绑定

转载地址:http://xoqzd.baihongyu.com/

你可能感兴趣的文章
阶段3 2.Spring_02.程序间耦合_3 程序的耦合和解耦的思路分析1
查看>>
阶段3 2.Spring_02.程序间耦合_5 编写工厂类和配置文件
查看>>
阶段3 2.Spring_01.Spring框架简介_05.spring的优势
查看>>
阶段3 2.Spring_02.程序间耦合_7 分析工厂模式中的问题并改造
查看>>
阶段3 2.Spring_02.程序间耦合_4 曾经代码中的问题分析
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_2 spring中的Ioc前期准备
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_4 ApplicationContext的三个实现类
查看>>
阶段3 2.Spring_02.程序间耦合_8 工厂模式解耦的升级版
查看>>
阶段3 2.Spring_03.Spring的 IOC 和 DI_6 spring中bean的细节之三种创建Bean对象的方式
查看>>
阶段3 2.Spring_04.Spring的常用注解_3 用于创建的Component注解
查看>>
阶段3 2.Spring_04.Spring的常用注解_2 常用IOC注解按照作用分类
查看>>
阶段3 2.Spring_09.JdbcTemplate的基本使用_5 JdbcTemplate在spring的ioc中使用
查看>>
阶段3 3.SpringMVC·_07.SSM整合案例_02.ssm整合之搭建环境
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_3、快速创建SpringBoot应用之手工创建web应用...
查看>>
阶段3 3.SpringMVC·_07.SSM整合案例_04.ssm整合之编写SpringMVC框架
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第1节零基础快速入门SpringBoot2.0_5、SpringBoot2.x的依赖默认Maven版本...
查看>>
阶段3 3.SpringMVC·_07.SSM整合案例_08.ssm整合之Spring整合MyBatis框架
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_9、SpringBoot基础HTTP其他提交方法请求实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第2节 SpringBoot接口Http协议开发实战_12、SpringBoot2.x文件上传实战...
查看>>
小D课堂 - 零基础入门SpringBoot2.X到实战_第4节 Springboot2.0单元测试进阶实战和自定义异常处理_19、SpringBoot个性化启动banner设置debug日志...
查看>>