【问题标题】:How does data-binding work in the Android IDE?数据绑定如何在 Android IDE 中工作?
【发布时间】:2023-03-25 06:07:01
【问题描述】:

数据绑定如何在 Android IDE 中工作?幕后流程是怎样的?

为了确定我在说什么,这个人试图解释它,但做了一个“嗯”的工作。我真的无法理解他。

https://youtu.be/scJGJgcbMGQ

【问题讨论】:

  • 啊,我没有读到关于 kotlin 的文章……我应该完成我的答案吗?
  • 没关系。它们几乎是一样的,我可以弄清楚它们之间的区别因为我这么说而被扔石头
  • 好的,我都编辑了。如果有帮助请采纳。

标签: android android-studio kotlin data-binding view


【解决方案1】:

什么是数据绑定?

数据绑定的原理是同步两个对象,使它们拥有相同的信息。这用于两个方向,从 UI 对象更改到下划线对象,反之亦然。在我们的示例 XML 和 android 中,数据绑定经常在两种不同的语言之间使用。数据绑定库提供了将数据和变量导入 XML 的所有必要方法。

数据绑定的优点是更少混乱的活动代码,也避免了 由于调用了未由框架创建或已销毁的视图,因此为空指针。

在此示例中,您将了解如何准备活动的 XML,为对象和辅助方法做好准备。


<data>
<!-- Import helper Method (static)-->
<import type="com.applications.startroutineactivity.helper.classes.Helper_MillisToString"/>
<!-- Prepare variable-->
<variable

name="Activity_Day"

type="com.applications.startroutineactivity.data_types_and_adapter.Obj_ActivityDay"/>

 </data>


<!-- this is an example how to use the object in xml-->
<TextView

android:id="@+id/tv_TakeTime_CurrentShownDateDateFormat"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginStart="8dp"

android:layout_alignTop="@+id/tv_TakeTime_UserHint"

android:clickable="true"

android:enabled="true"

android:hint="12.01.2018"

android:onClick="oc_tv_TakeTime_CurrentShownDateDateFormat"

android:text="@{Helper_MillisToString.getStringOutMillis(Activity_Day.getActivity_Day())}"

android:textColor="@color/Mercedes_WHITE"

android:textColorHint="@color/Mercedes_GREY"

android:textSize="@dimen/dim_TextSize_Normal_Big"

app:layout_constraintBottom_toBottomOf="@+id/bt_TakeTime_nextDate"

app:layout_constraintStart_toEndOf="@+id/bt_TakeTime_lastDate"

app:layout_constraintTop_toTopOf="@+id/bt_TakeTime_nextDate"/>

在你的活动类中使用它:

ActivityTaketimeBinding mainBinding; //This always refers to the layout file name "_" turns into upperCase

//Use this in onCreate()

mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_taketime);

//Use this to set an object
mainBinding.setActivityDay();//.setXXX is referring to the name of the variable in the XML file.

要启用数据绑定,请将其添加到您的 build.gradle 文件中。

dataBinding {

enabled =true

}

buildToolsVersion '28.0.3'

同步、清除和重建。 还要确保已从 SDK 管理器安装了所有支持包。

使用this 教程,非常棒。

【讨论】:

  • 您的回答向我展示了如何启用数据绑定以及数据绑定的用途。尽管您的答案很有用,但它并不能解释实际发生的幕后过程。我更新了我的问题以澄清我在寻找什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 2016-06-11
  • 1970-01-01
  • 2014-05-17
  • 2015-09-28
相关资源
最近更新 更多