Thư viện liên kết dữ liệu là một thư viện hỗ trợ cho phép bạn liên kết giao diện người dùng
các thành phần trong bố cục đến các nguồn dữ liệu trong ứng dụng bằng cách sử dụng hàm khai báo
thay vì theo phương thức lập trình.
Bố cục thường được xác định trong các hoạt động có mã gọi khung giao diện người dùng
. Ví dụ: mã bên dưới gọi findViewById() để tìm tiện ích TextView và liên kết tiện ích đó với thuộc tính userName của
Biến viewModel:
Kotlin
findViewById<TextView>(R.id.sample_text).apply {
text = viewModel.userName
}
Ví dụ sau cho thấy cách sử dụng Thư viện liên kết dữ liệu để gán văn bản
vào tiện ích ngay trong tệp bố cục. Việc này giúp bạn không cần phải gọi bất kỳ
mã Java hiển thị ở trên. Lưu ý rằng việc sử dụng cú pháp @{} trong bài tập
biểu thức:
<TextView
android:text="@{viewmodel.userName}" />
Việc liên kết các thành phần trong tệp bố cục cho phép bạn xoá nhiều lệnh gọi khung giao diện người dùng trong
các hoạt động của bạn, giúp chúng trở nên đơn giản và dễ duy trì hơn. Việc này cũng có thể
cải thiện hiệu suất của ứng dụng và giúp ngăn chặn lỗi rò rỉ bộ nhớ cũng như con trỏ rỗng
ngoại lệ.
Sử dụng Thư viện liên kết dữ liệu
Hãy xem các trang sau để tìm hiểu cách sử dụng Thư viện liên kết dữ liệu trong
Ứng dụng Android.
Tìm hiểu cách chuẩn bị sẵn sàng cho môi trường phát triển để làm việc với Dữ liệu
Thư viện liên kết, bao gồm cả tính năng hỗ trợ mã liên kết dữ liệu trong Android Studio.
Ngôn ngữ biểu thức cho phép bạn viết biểu thức kết nối
vào các chế độ xem trong bố cục. Thư viện liên kết dữ liệu tự động
tạo các lớp cần thiết để liên kết thành phần hiển thị trong bố cục với dữ liệu của bạn
. Thư viện này cung cấp các tính năng như nhập, biến và
bao gồm dữ liệu mà bạn có thể sử dụng trong bố cục của mình.
Các tính năng này của thư viện cùng tồn tại liền mạch với các bố cục hiện có của bạn.
Ví dụ: các biến liên kết có thể được sử dụng trong biểu thức được xác định
bên trong một phần tử data là thành phần đồng cấp với phần tử gốc của bố cục giao diện người dùng.
Cả hai phần tử đều được gói trong một thẻ layout, như minh hoạ sau đây
ví dụ:
Thư viện liên kết dữ liệu cung cấp các lớp và phương thức để dễ dàng quan sát dữ liệu
cho các thay đổi. Bạn không phải lo lắng về việc làm mới giao diện người dùng khi
các thay đổi về nguồn dữ liệu cơ bản. Bạn có thể tạo các biến hoặc
thuộc tính có thể quan sát được. Thư viện này cho phép bạn tạo đối tượng, trường hoặc
tập hợp có thể quan sát được.
Thư viện liên kết dữ liệu tạo các lớp liên kết dùng để truy cập vào
các biến và khung hiển thị của bố cục. Trang này hướng dẫn bạn cách sử dụng và tuỳ chỉnh
các lớp liên kết được tạo.
Mỗi biểu thức bố cục đều có một bộ chuyển đổi liên kết giúp
bắt buộc phải có lệnh gọi khung để đặt các thuộc tính hoặc trình nghe tương ứng. Cho
Ví dụ: phương thức điều hợp liên kết (binding adapter) có thể đảm nhận việc gọi phương thức setText()
để đặt thuộc tính văn bản hoặc gọi phương thức setOnClickListener() để thêm thuộc tính
trình nghe sự kiện nhấp chuột. Các bộ chuyển đổi liên kết phổ biến nhất, chẳng hạn như
các bộ chuyển đổi cho thuộc tính android:text được dùng trong các ví dụ trên trang này,
có sẵn để bạn dùng trong gói android.databinding.adapters.
Để biết danh sách các bộ chuyển đổi liên kết phổ biến, hãy xem
bộ chuyển đổi.
Bạn cũng có thể tạo bộ chuyển đổi tuỳ chỉnh như trong ví dụ sau:
Kotlin
@BindingAdapter("app:goneUnless")
fun goneUnless(view: View, visible: Boolean) {
view.visibility = if (visible) View.VISIBLE else View.GONE
}
Thư viện hỗ trợ Android bao gồm Cấu trúc
Các thành phần mà bạn có thể dùng để
thiết kế các ứng dụng mạnh mẽ, có thể kiểm thử và bảo trì. Bạn có thể sử dụng thẻ Cấu trúc
Các thành phần có Thư viện liên kết dữ liệu để đơn giản hoá quá trình phát triển hơn nữa
của giao diện người dùng.
Thư viện liên kết dữ liệu hỗ trợ liên kết dữ liệu hai chiều. Ký hiệu dùng cho
loại liên kết này hỗ trợ khả năng nhận các thay đổi về dữ liệu đối với một tài sản
và theo dõi thông tin cập nhật của người dùng về tài sản đó cùng một lúc.
Tài nguyên khác
Để tìm hiểu thêm về liên kết dữ liệu, hãy tham khảo
các tài nguyên khác.
Nội dung và mã mẫu trên trang này phải tuân thủ các giấy phép như mô tả trong phần Giấy phép nội dung. Java và OpenJDK là nhãn hiệu hoặc nhãn hiệu đã đăng ký của Oracle và/hoặc đơn vị liên kết của Oracle.
Cập nhật lần gần đây nhất: 2024-08-23 UTC.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2024-08-23 UTC."],[],[],null,["# Data Binding Library\nPart of [Android Jetpack](/jetpack).\n=========================================================\n\nThe Data Binding Library is a support library that allows you to bind UI\ncomponents in your layouts to data sources in your app using a declarative\nformat rather than programmatically.\n\nLayouts are often defined in activities with code that calls UI framework\nmethods. For example, the code below calls [findViewById()](/reference/android/app/Activity#findViewById(int)) to find a [TextView](/reference/android/widget/TextView) widget and bind it to the `userName` property of the\n`viewModel` variable: \n\n### Kotlin\n\n```kotlin\nfindViewById\u003cTextView\u003e(R.id.sample_text).apply {\n text = viewModel.userName\n}\n```\n\n### Java\n\n```java\nTextView textView = findViewById(R.id.sample_text);\ntextView.setText(viewModel.getUserName());\n```\n\nThe following example shows how to use the Data Binding Library to assign text\nto the widget directly in the layout file. This removes the need to call any of\nthe Java code shown above. Note the use of `@{}` syntax in the assignment\nexpression: \n\n \u003cTextView\n android:text=\"@{viewmodel.userName}\" /\u003e\n\nBinding components in the layout file lets you remove many UI framework calls in\nyour activities, making them simpler and easier to maintain. This can also\nimprove your app's performance and help prevent memory leaks and null pointer\nexceptions.\n| **Note:** In many cases, [view binding](/topic/libraries/view-binding) can provide the same benefits as data binding with simpler implementation and better performance. If you are using data binding primarily to replace `findViewById()` calls, consider using view binding instead.\n\nUsing the Data Binding Library\n------------------------------\n\nUse the following pages to learn how to use the Data Binding Library in your\nAndroid apps.\n\n[**Get started**](/topic/libraries/data-binding/start)\n: Learn how to get your development environment ready to work with the Data\n Binding Library, including support for data binding code in Android Studio.\n\n[**Layouts and binding expressions**](/topic/libraries/data-binding/expressions)\nThe expression language allows you to write expressions that connect\nvariables to the views in the layout. The Data Binding Library automatically\ngenerates the classes required to bind the views in the layout with your data\nobjects. The library provides features such as imports, variables, and\nincludes that you can use in your layouts.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\nThese features of the library coexist seamlessly with your existing layouts.\nFor example, the binding variables that can be used in expressions are defined\ninside a `data` element that is a sibling of the UI layout's root element.\nBoth elements are wrapped in a `layout` tag, as shown in the following\nexample:\n\n\u003cbr /\u003e\n\n \u003clayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\u003e\n \u003cdata\u003e\n \u003cvariable\n name=\"viewmodel\"\n type=\"com.myapp.data.ViewModel\" /\u003e\n \u003c/data\u003e\n \u003cConstraintLayout... /\u003e \u003c!-- UI layout's root element --\u003e\n \u003c/layout\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n[**Work with observable data objects**](/topic/libraries/data-binding/observability)\n: The Data Binding Library provides classes and methods to easily observe data\n for changes. You don't have to worry about refreshing the UI when the\n underlying data source changes. You can make your variables or their\n properties observable. The library allows you to make objects, fields, or\n collections observable.\n\n[**Generated binding classes**](/topic/libraries/data-binding/generated-binding)\n: The Data Binding Library generates binding classes that are used to access the\n layout's variables and views. This page shows you how to use and customize\n generated binding classes.\n\n[**Binding adapters**](/topic/libraries/data-binding/binding-adapters)\n: For every layout expression, there is a binding adapter that makes the\n framework calls required to set the corresponding properties or listeners. For\n example, the binding adapter can take care of calling the `setText()` method\n to set the text property or call the `setOnClickListener()` method to add a\n listener to the click event. The most common binding adapters, such as the\n adapters for the `android:text` property used in the examples in this page,\n are available for you to use in the `android.databinding.adapters` package.\n For a list of the common binding adapters, see\n [adapters](https://android.googlesource.com/platform/frameworks/data-binding/+/refs/heads/studio-master-dev/extensions/baseAdapters/src/main/java/androidx/databinding/adapters).\nYou can also create custom adapters, as shown in the following example: \n\n### Kotlin\n\n```kotlin\n@BindingAdapter(\"app:goneUnless\")\nfun goneUnless(view: View, visible: Boolean) {\n view.visibility = if (visible) View.VISIBLE else View.GONE\n}\n```\n\n### Java\n\n```java\n@BindingAdapter(\"app:goneUnless\")\npublic static void goneUnless(View view, Boolean visible) {\n view.visibility = visible ? View.VISIBLE : View.GONE;\n}\n```\n\n[**Bind layout views to Architecture Components**](/topic/libraries/data-binding/architecture)\n: The Android Support Library includes the [Architecture\n Components](/topic/libraries/architecture), which you can use to\n design robust, testable, and maintainable apps. You can use the Architecture\n Components with the Data Binding Library to further simplify the development\n of your UI.\n\n[**Two-way data binding**](/topic/libraries/data-binding/two-way)\n: The Data Binding Library supports two-way data binding. The notation used for\n this type of binding supports the ability to receive data changes to a property\n and listen to user updates to that property at the same time.\n\nAdditional resources\n--------------------\n\nTo learn more about data binding, consult the following\nadditional resources.\n\n### Samples\n\n- [Android Data Binding Library samples](https://github.com/android/databinding-samples)\n\n### Codelabs\n\n- [Android Data Binding codelab](https://codelabs.developers.google.com/codelabs/android-databinding)\n\n### Blog posts\n\n- [Android Data Binding Library --- From Observable Fields to LiveData in two steps](https://medium.com/androiddevelopers/android-data-binding-library-from-observable-fields-to-livedata-in-two-steps-690a384218f2)\n- [Data Binding --- Lessons Learnt](https://medium.com/androiddevelopers/data-binding-lessons-learnt-4fd16576b719)\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Binding adapters {:#binding-adapters}](/topic/libraries/data-binding/binding-adapters)\n- [Layouts and binding expressions](/topic/libraries/data-binding/expressions)\n- [Generated binding classes {: #binding-classes}](/topic/libraries/data-binding/generated-binding)"]]