Tiếp theo, hãy làm theo hướng dẫn Tạo tiện ích đơn giản để tạo và xác định thông tin tiện ích ứng dụng trong tệp @xml/my_app_widget_info.
Điểm khác biệt duy nhất đối với tính năng Xem nhanh là không có tệp XML initialLayout, nhưng bạn phải xác định một tệp XML. Bạn có thể sử dụng bố cục tải được xác định trước trong thư viện:
Tạo một lớp mới mở rộng từ GlanceAppWidget và ghi đè phương thức provideGlance. Đây là phương thức mà bạn có thể tải dữ liệu cần thiết để hiển thị tiện ích:
classMyAppWidget:GlanceAppWidget(){overridesuspendfunprovideGlance(context:Context,id:GlanceId){// In this method, load data needed to render the AppWidget.// Use `withContext` to switch to another thread for long running// operations.provideContent{// create your AppWidget hereText("Hello World")}}}
Tạo thực thể trong glanceAppWidget trên GlanceAppWidgetReceiver:
classMyAppWidgetReceiver:GlanceAppWidgetReceiver(){// Let MyAppWidgetReceiver know which GlanceAppWidget to useoverridevalglanceAppWidget:GlanceAppWidget=MyAppWidget()}
Bây giờ, bạn đã định cấu hình AppWidget bằng Glance.
Tạo giao diện người dùng
Đoạn mã sau đây minh hoạ cách tạo giao diện người dùng:
/* Import Glance Composables In the event there is a name clash with the Compose classes of the same name, you may rename the imports per https://kotlinlang.org/docs/packages.html#imports using the `as` keyword.import androidx.glance.Buttonimport androidx.glance.layout.Columnimport androidx.glance.layout.Rowimport androidx.glance.text.Text*/classMyAppWidget:GlanceAppWidget(){overridesuspendfunprovideGlance(context:Context,id:GlanceId){// Load data needed to render the AppWidget.// Use `withContext` to switch to another thread for long running// operations.provideContent{// create your AppWidget hereMyContent()}}@ComposableprivatefunMyContent(){Column(modifier=GlanceModifier.fillMaxSize(),verticalAlignment=Alignment.Top,horizontalAlignment=Alignment.CenterHorizontally){Text(text="Where to?",modifier=GlanceModifier.padding(12.dp))Row(horizontalAlignment=Alignment.CenterHorizontally){Button(text="Home",onClick=actionStartActivity<MyActivity>())Button(text="Work",onClick=actionStartActivity<MyActivity>())}}}}
Ở cấp cao nhất Column, các mục được đặt theo chiều dọc, lần lượt từng mục.
Column mở rộng kích thước để khớp với không gian có sẵn (thông qua GlanceModifier và căn chỉnh nội dung của nó ở trên cùng (verticalAlignment) và căn giữa theo chiều ngang (horizontalAlignment).
Nội dung của Column được xác định bằng lambda. Thứ tự rất quan trọng.
Mục đầu tiên trong Column là thành phần Text có khoảng đệm 12.dp.
Mục thứ hai là Row, trong đó các mục được đặt theo chiều ngang, kế tiếp nhau, với hai Buttons được căn giữa theo chiều ngang (horizontalAlignment). Màn hình hiển thị cuối cùng phụ thuộc vào không gian có sẵn.
Hình ảnh sau đây là ví dụ về giao diện có thể xuất hiện:
Hình 1. Giao diện người dùng mẫu.
Bạn có thể thay đổi các giá trị căn chỉnh hoặc áp dụng các giá trị đối tượng sửa đổi khác nhau (chẳng hạn như khoảng đệm) để thay đổi vị trí và kích thước của các thành phần. Hãy xem tài liệu tham khảo để biết danh sách đầy đủ các thành phần, tham số và đối tượng sửa đổi có sẵn cho từng lớp.
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: 2025-08-24 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: 2025-08-24 UTC."],[],[],null,["The following sections describe how to create a simple app widget with Glance.\n| **Key Point:** Glance provides a modern approach to build app widgets using Compose, but is restricted by the limitations of `AppWidgets` and `RemoteViews`. Therefore, Glance uses different *composables* from the Jetpack Compose UI.\n\nDeclare the `AppWidget` in the Manifest\n\nAfter completing the [setup steps](/develop/ui/compose/glance/setup), declare the [`AppWidget`](/guide/topics/appwidgets) and its\nmetadata in your app.\n\n1. Extend the `AppWidget` receiver from `GlanceAppWidgetReceiver`:\n\n\n ```kotlin\n class MyAppWidgetReceiver : GlanceAppWidgetReceiver() {\n override val glanceAppWidget: GlanceAppWidget = TODO(\"Create GlanceAppWidget\")\n }https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L100-L102\n ```\n\n \u003cbr /\u003e\n\n2. Register the provider of the app widget in your `AndroidManifest.xml` file\n and the associated metadata file:\n\n \u003creceiver android:name=\".glance.MyReceiver\"\n android:exported=\"true\"\u003e\n \u003cintent-filter\u003e\n \u003caction android:name=\"android.appwidget.action.APPWIDGET_UPDATE\" /\u003e\n \u003c/intent-filter\u003e\n \u003cmeta-data\n android:name=\"android.appwidget.provider\"\n android:resource=\"@xml/my_app_widget_info\" /\u003e\n \u003c/receiver\u003e \n https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/AndroidManifest.xml#L61-L69\n\nAdd the `AppWidgetProviderInfo` metadata\n\nNext, follow the [Create a simple widget](/guide/topics/appwidgets#MetaData) guide to create and define the app\nwidget info in the `@xml/my_app_widget_info` file.\n\nThe only difference for Glance is that there is no `initialLayout` XML, but\nyou must define one. You can use the predefined loading layout provided in\nthe library: \n\n \u003cappwidget-provider xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:initialLayout=\"@layout/glance_default_loading_layout\"\u003e\n \u003c/appwidget-provider\u003e \n https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/res/xml/my_app_widget_info.xml#L18-L20\n\nDefine `GlanceAppWidget`\n\n1. Create a new class that extends from [`GlanceAppWidget`](/reference/kotlin/androidx/glance/appwidget/GlanceAppWidget) and overrides the\n `provideGlance` method. This is the method where you can load data that is\n needed to render your widget:\n\n | **Note:** `provideGlance` runs on the main thread. To perform any long running operations in `provideGlance`, switch to another thread using `withContext`. See [Use coroutines for main-safety](/kotlin/coroutines/coroutines-adv#main-safety) for more details on how to run outside of the main thread.\n\n\n ```kotlin\n class MyAppWidget : GlanceAppWidget() {\n\n override suspend fun provideGlance(context: Context, id: GlanceId) {\n\n // In this method, load data needed to render the AppWidget.\n // Use `withContext` to switch to another thread for long running\n // operations.\n\n provideContent {\n // create your AppWidget here\n Text(\"Hello World\")\n }\n }\n }https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L116-L129\n ```\n\n \u003cbr /\u003e\n\n2. Instantiate it in the `glanceAppWidget` on your `GlanceAppWidgetReceiver`:\n\n\n ```kotlin\n class MyAppWidgetReceiver : GlanceAppWidgetReceiver() {\n\n // Let MyAppWidgetReceiver know which GlanceAppWidget to use\n override val glanceAppWidget: GlanceAppWidget = MyAppWidget()\n }https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L108-L112\n ```\n\n \u003cbr /\u003e\n\nYou've now configured an `AppWidget` using Glance.\n\nCreate UI\n\nThe following snippet demonstrates how to create the UI:\n\n\n```kotlin\n/* Import Glance Composables\n In the event there is a name clash with the Compose classes of the same name,\n you may rename the imports per https://kotlinlang.org/docs/packages.html#imports\n using the `as` keyword.\n\nimport androidx.glance.Button\nimport androidx.glance.layout.Column\nimport androidx.glance.layout.Row\nimport androidx.glance.text.Text\n*/\nclass MyAppWidget : GlanceAppWidget() {\n\n override suspend fun provideGlance(context: Context, id: GlanceId) {\n // Load data needed to render the AppWidget.\n // Use `withContext` to switch to another thread for long running\n // operations.\n\n provideContent {\n // create your AppWidget here\n MyContent()\n }\n }\n\n @Composable\n private fun MyContent() {\n Column(\n modifier = GlanceModifier.fillMaxSize(),\n verticalAlignment = Alignment.Top,\n horizontalAlignment = Alignment.CenterHorizontally\n ) {\n Text(text = \"Where to?\", modifier = GlanceModifier.padding(12.dp))\n Row(horizontalAlignment = Alignment.CenterHorizontally) {\n Button(\n text = \"Home\",\n onClick = actionStartActivity\u003cMyActivity\u003e()\n )\n Button(\n text = \"Work\",\n onClick = actionStartActivity\u003cMyActivity\u003e()\n )\n }\n }\n }\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/main/java/com/example/compose/snippets/glance/GlanceSnippets.kt#L135-L178\n```\n\n\u003cbr /\u003e\n\nThe preceding code sample does the following:\n\n- In the top level [`Column`](/reference/kotlin/androidx/glance/layout/package-summary#column), items are placed vertically one after each other.\n- The `Column` expands its size to match the available space (via the [`GlanceModifier`](/reference/kotlin/androidx/glance/GlanceModifier)) and aligns its content to the top (`verticalAlignment`) and centers it horizontally (`horizontalAlignment`).\n- The `Column`'s content is defined using the lambda. The order matters.\n - The first item in the `Column` is a `Text` component with `12.dp` of padding.\n - The second item is a [`Row`](/reference/kotlin/androidx/glance/layout/package-summary#row), where items are placed horizontally one after each other, with two [`Buttons`](/reference/kotlin/androidx/glance/package-summary#button) centered horizontally (`horizontalAlignment`). The final display depends on the available space. The following image is an example of what it may look like:\n\n**Figure 1.** An example UI.\n\nYou can change the alignment values or apply different modifier values (such as\npadding) to change the placement and size of the components. See the [reference\ndocumentation](/reference/kotlin/androidx/glance/package-summary) for a full list of components, parameters, and available\nmodifiers for each class."]]