Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
WebView là một thành phần thường được sử dụng. Thành phần này cung cấp hệ thống quản lý trạng thái tiên tiến. WebView phải giữ nguyên trạng thái và vị trí cuộn khi có những thay đổi về cấu hình. WebView có thể rời khỏi vị trí cuộn khi người dùng xoay thiết bị hoặc mở gập màn hình điện thoại, buộc người dùng phải cuộn lại từ đầu WebView đến vị trí cuộn trước đó.
WebView thích hợp trong việc quản lý trạng thái. Bạn có thể tận dụng tính năng này bằng cách quản lý càng nhiều thay đổi cấu hình càng tốt để giảm thiểu số lần tạo lại WebView. Ứng dụng của bạn nên xử lý các thay đổi về cấu hình vì việc tạo lại hoạt động (cách xử lý các thay đổi về cấu hình của hệ thống) sẽ tạo lại WebView, khiến WebView bị mất trạng thái.
Quản lý trạng thái
Tránh tạo lại Activity nhiều nhất có thể trong quá trình thay đổi cấu hình và để WebView mất hiệu lực để thành phần này có thể thay đổi kích thước trong khi vẫn giữ nguyên trạng thái.
Cách quản lý trạng thái WebView:
Khai báo các thay đổi về cấu hình do ứng dụng của bạn xử lý
Vô hiệu hoá trạng thái WebView
1. Thêm thay đổi cấu hình vào tệp AndroidManifest.xml của ứng dụng
Tránh tạo lại hoạt động bằng cách chỉ định thay đổi cấu hình do ứng dụng của bạn xử lý (thay vì để hệ thống xử lý):
Bước này chỉ áp dụng cho hệ thống khung hiển thị, vì Jetpack Compose không cần vô hiệu hoá bất kỳ thứ gì để đổi kích thước các phần tử Composable một cách chính xác. Tuy nhiên, Compose sẽ thường xuyên tạo lại WebView nếu không được quản lý đúng cách.
Điểm chính
android:configChanges: Thuộc tính của phần tử tệp kê khai <activity>. Liệt kê các thay đổi về cấu hình do hoạt động xử lý.
View#invalidate(): Phương thức khiến khung hiển thị được vẽ lại. Kế thừa từ WebView.
Kết quả
Giờ đây, các thành phần WebView của ứng dụng đã giữ nguyên trạng thái và vị trí cuộn khi cấu hình có nhiều sự thay đổi, như thay đổi kích thước, thay đổi hướng hoặc trạng thái gập/mở thiết bị.
Các bộ sưu tập chứa hướng dẫn này
Hướng dẫn này là một phần của các bộ sưu tập Hướng dẫn nhanh được tuyển chọn này, bao gồm các mục tiêu phát triển Android rộng hơn:
Tối ưu hoá cho màn hình lớn
Cho phép ứng dụng của bạn hỗ trợ trải nghiệm người dùng được tối ưu hoá trên máy tính bảng, thiết bị có thể gập lại và thiết bị ChromeOS.
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-02-06 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-02-06 UTC."],[],[],null,["# Manage WebView state\n\n[`WebView`](/reference/kotlin/android/webkit/WebView) is a commonly used\ncomponent that offers an advanced system for state management. A `WebView`\nmust maintain its state and scroll position across configuration changes. A\n`WebView` can lose scroll position when the user rotates the device or unfolds\na foldable phone, which forces the user to scroll again from the top of the\n`WebView` to the previous scroll position.\n\n`WebView` is good at managing its state. You can take advantage of this quality\nby managing as many configuration changes as possible to minimize the number of\ntimes a `WebView` is recreated. Your app should handle configuration changes\nbecause activity recreation (the system's way of handling configuration\nchanges) recreates the `WebView`, which causes the `WebView` to lose state.\n\nManage state\n------------\n\nAvoid [`Activity`](/reference/kotlin/android/app/Activity) recreation as much as\npossible during configuration changes, and let the `WebView` invalidate so it\ncan resize while retaining its state.\n\nTo manage `WebView` state:\n\n- Declare configuration changes handled by your app\n- Invalidate the `WebView` state\n\n#### 1. Add configuration changes to your app's `AndroidManifest.xml` file\n\nAvoid activity recreation by specifying the configuration changes handled by\nyour app (rather than by the system): \n\n \u003cactivity\n android:name=\".MyActivity\"\n android:configChanges=\"screenLayout|orientation|screenSize\n |keyboard|keyboardHidden|smallestScreenSize\" /\u003e\n\n| **Note:** While this nonexhaustive list of configuration changes might be okay for many applications, make sure to manage the configuration changes that make the most sense for your case based on how your users interact with the app, for how long, and when. To find the best combination of configurations for your app, see [`android:configChanges`](/guide/topics/manifest/activity-element#config).\n\n#### 2. Invalidate `WebView` whenever your app receives a configuration change\n\n### Kotlin\n\n```kotlin\noverride fun onConfigurationChanged(newConfig: Configuration) {\n super.onConfigurationChanged(newConfig)\n webView.invalidate()\n}\n```\n\n### Java\n\n```java\n@Override\npublic void onConfigurationChanged(@NonNull Configuration newConfig) {\n super.onConfigurationChanged(newConfig);\n webview.invalidate();\n}\n```\n\nThis step applies only to the view system, as Jetpack Compose does not need to\ninvalidate anything to resize\n[`Composable`](/reference/kotlin/androidx/compose/runtime/Composable) elements\ncorrectly. However, Compose recreates a `WebView` often if not managed\ncorrectly.\n\nKey points\n----------\n\n- [`android:configChanges`](/guide/topics/manifest/activity-element#config): Attribute of the manifest `\u003cactivity\u003e` element. Lists the configuration changes handled by the activity.\n- [`View#invalidate()`](/reference/kotlin/android/view/View#invalidate_2): Method that causes a view to be redrawn. Inherited by `WebView`.\n\nResults\n-------\n\nYour app's `WebView` components now retain their state and scroll position\nacross multiple configuration changes, from resizing to orientation changes\nto device folding and unfolding.\n\nCollections that contain this guide\n-----------------------------------\n\nThis guide is part of these curated Quick Guide collections that cover\nbroader Android development goals: \n\n### Optimize for large screens\n\nEnable your app to support an optimized user experience on tablets, foldables, and ChromeOS devices. \n[Quick guide collection](/quick-guides/collections/optimize-for-large-screens) \n\nHave questions or feedback\n--------------------------\n\nGo to our frequently asked questions page and learn about quick guides or reach out and let us know your thoughts. \n[Go to FAQ](/quick-guides/faq) [Leave feedback](https://issuetracker.google.com/issues/new?component=1573691&template=1993320)"]]