Các tiện ích bộ sưu tập chuyên hiển thị nhiều phần tử cùng loại, chẳng hạn như bộ sưu tập hình ảnh từ ứng dụng thư viện, bài viết từ một ứng dụng tin tức hoặc tin nhắn từ một ứng dụng giao tiếp. Các tiện ích bộ sưu tập thường tập trung vào hai trường hợp sử dụng: duyệt qua bộ sưu tập và mở một phần tử của bộ sưu tập ở chế độ xem chi tiết. Tiện ích Bộ sưu tập có thể cuộn theo chiều dọc.
Các tiện ích này sử dụng RemoteViewsService
để hiển thị các bộ sưu tập được dữ liệu từ xa hỗ trợ, chẳng hạn như từ một nhà cung cấp nội dung. Tiện ích này trình bày dữ liệu bằng một trong các kiểu khung hiển thị sau, còn gọi là khung hiển thị bộ sưu tập:
ListView
- Một khung hiển thị hiển thị các mục trong danh sách cuộn theo chiều dọc.
GridView
- Một khung hiển thị cho thấy các mục trong lưới cuộn hai chiều.
StackView
- Chế độ xem thẻ xếp chồng – tương tự như một trò chơi rolodex – trong đó người dùng có thể kéo thẻ trước lên hoặc xuống để xem thẻ trước hoặc thẻ tiếp theo tương ứng.
AdapterViewFlipper
ViewAnimator
đơn giản dựa trên bộ chuyển đổi, tạo ảnh động giữa 2 hoặc nhiều khung hiển thị. Mỗi lần chỉ có một trẻ xuất hiện.
Vì các thành phần hiển thị bộ sưu tập này cho thấy các bộ sưu tập được dữ liệu từ xa hỗ trợ, nên chúng sử dụng Adapter
để liên kết giao diện người dùng với dữ liệu của chúng. Adapter
liên kết các mục riêng lẻ từ một tập dữ liệu với các đối tượng View
riêng lẻ.
Vì các thành phần hiển thị bộ sưu tập này được bộ chuyển đổi hỗ trợ nên khung Android phải có cấu trúc bổ sung để hỗ trợ việc sử dụng các thành phần này trong các tiện ích. Trong ngữ cảnh
của một tiện ích, Adapter
được thay thế bằng
RemoteViewsFactory
,
là một trình bao bọc mỏng xung quanh giao diện Adapter
. Khi được yêu cầu đối với một mục cụ thể trong bộ sưu tập, RemoteViewsFactory
sẽ tạo và trả về mục cho bộ sưu tập dưới dạng đối tượng RemoteViews
. Để đưa khung hiển thị bộ sưu tập vào tiện ích, hãy triển khai RemoteViewsService
và RemoteViewsFactory
.
RemoteViewsService
là một dịch vụ cho phép bộ chuyển đổi từ xa yêu cầu các đối tượng RemoteViews
. RemoteViewsFactory
là giao diện của trình chuyển đổi giữa một khung hiển thị bộ sưu tập (chẳng hạn như ListView
, GridView
và StackView
) và dữ liệu cơ bản của khung hiển thị đó. Từ StackWidget
mẫu, dưới đây là ví dụ về mã nguyên mẫu để triển khai dịch vụ và giao diện này:
Kotlin
class StackWidgetService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { return StackRemoteViewsFactory(this.applicationContext, intent) } } class StackRemoteViewsFactory( private val context: Context, intent: Intent ) : RemoteViewsService.RemoteViewsFactory { // See the RemoteViewsFactory API reference for the full list of methods to // implement. }
Java
public class StackWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new StackRemoteViewsFactory(this.getApplicationContext(), intent); } } class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { // See the RemoteViewsFactory API reference for the full list of methods to // implement. }
Ứng dụng mẫu
Các đoạn trích mã trong phần này cũng được lấy từ mẫu StackWidget
:
Mẫu này bao gồm một ngăn xếp gồm 10 khung hiển thị cho thấy các giá trị từ 0 đến 9. Tiện ích mẫu có các hành vi chính sau:
Người dùng có thể hất khung hiển thị trên cùng theo chiều dọc trong tiện ích để hiển thị khung hiển thị tiếp theo hoặc trước đó. Đây là hành vi
StackView
tích hợp sẵn.Khi không cần người dùng tương tác, tiện ích này sẽ tự động chuyển qua các thành phần hiển thị theo trình tự, chẳng hạn như trình chiếu. Nguyên nhân là do chế độ cài đặt
android:autoAdvanceViewId="@id/stack_view"
trong tệpres/xml/stackwidgetinfo.xml
. Chế độ cài đặt này áp dụng cho mã khung hiển thị, trong trường hợp này là mã khung hiển thị của khung hiển thị ngăn xếp.Nếu người dùng chạm vào khung hiển thị trên cùng, tiện ích sẽ hiển thị
Toast
thông báo "Touched view n," trong đó n là chỉ mục được chạm (vị trí của khung hiển thị được chạm). Để thảo luận thêm về cách triển khai hành vi, hãy xem phần Thêm hành vi vào từng mục.
Triển khai tiện ích với bộ sưu tập
Để triển khai một tiện ích có các bộ sưu tập, hãy làm theo quy trình để triển khai bất kỳ tiện ích nào, sau đó là một vài bước bổ sung: sửa đổi tệp kê khai, thêm chế độ xem bộ sưu tập vào bố cục tiện ích và sửa đổi lớp con AppWidgetProvider
.
Tệp kê khai cho các tiện ích có bộ sưu tập
Ngoài các yêu cầu nêu trong bài viết Khai báo tiện ích trong tệp kê khai, bạn cần cho phép các tiện ích có bộ sưu tập có thể liên kết với RemoteViewsService
của bạn. Hãy thực hiện việc này bằng cách khai báo dịch vụ trong tệp kê khai với quyền BIND_REMOTEVIEWS
.
Điều này ngăn các ứng dụng khác tự do truy cập vào dữ liệu của tiện ích của bạn.
Ví dụ: khi tạo một tiện ích sử dụng RemoteViewsService
để điền sẵn khung hiển thị bộ sưu tập, mục nhập tệp kê khai có thể có dạng như sau:
<service android:name="MyWidgetService"
android:permission="android.permission.BIND_REMOTEVIEWS" />
Trong ví dụ này, android:name="MyWidgetService"
đề cập đến lớp con của RemoteViewsService
.
Bố cục cho các tiện ích có bộ sưu tập
Yêu cầu chính đối với tệp XML bố cục tiện ích là tệp này bao gồm một trong các khung hiển thị bộ sưu tập: ListView
, GridView
, StackView
hoặc AdapterViewFlipper
. Dưới đây là tệp widget_layout.xml
cho mẫu StackWidget
:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<StackView
android:id="@+id/stack_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:loopViews="true" />
<TextView
android:id="@+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="@drawable/widget_item_background"
android:textColor="#ffffff"
android:textStyle="bold"
android:text="@string/empty_view_text"
android:textSize="20sp" />
</FrameLayout>
Lưu ý rằng khung hiển thị trống phải là đồng cấp của khung hiển thị bộ sưu tập mà khung hiển thị trống biểu thị trạng thái trống.
Ngoài tệp bố cục cho toàn bộ tiện ích, hãy tạo một tệp bố cục khác xác định bố cục cho từng mục trong bộ sưu tập, ví dụ: bố cục cho mỗi cuốn sách trong bộ sách. Mẫu StackWidget
chỉ có một tệp bố cục mục là widget_item.xml
, vì tất cả các mục đều sử dụng cùng một bố cục.
Lớp AppWidgetProvider cho các tiện ích có bộ sưu tập
Giống như các tiện ích thông thường, phần lớn mã trong lớp con AppWidgetProvider
của bạn thường nằm trong onUpdate()
.
Điểm khác biệt lớn nhất trong cách triển khai onUpdate()
khi tạo tiện ích có các bộ sưu tập là bạn phải gọi setRemoteAdapter()
. Điều này cho chế độ xem bộ sưu tập biết nơi để lấy dữ liệu.
Sau đó, RemoteViewsService
có thể trả về phương thức triển khai RemoteViewsFactory
và tiện ích này có thể phân phát dữ liệu thích hợp. Khi bạn gọi phương thức này, hãy chuyển một ý định trỏ đến phương thức triển khai RemoteViewsService
và mã tiện ích chỉ định tiện ích cần cập nhật.
Ví dụ: dưới đây là cách mẫu StackWidget
triển khai phương thức gọi lại onUpdate()
để đặt RemoteViewsService
làm bộ chuyển đổi từ xa cho tập hợp tiện ích:
Kotlin
override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // Update each of the widgets with the remote adapter. appWidgetIds.forEach { appWidgetId -> // Set up the intent that starts the StackViewService, which // provides the views for this collection. val intent = Intent(context, StackWidgetService::class.java).apply { // Add the widget ID to the intent extras. putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME)) } // Instantiate the RemoteViews object for the widget layout. val views = RemoteViews(context.packageName, R.layout.widget_layout).apply { // Set up the RemoteViews object to use a RemoteViews adapter. // This adapter connects to a RemoteViewsService through the // specified intent. // This is how you populate the data. setRemoteAdapter(R.id.stack_view, intent) // The empty view is displayed when the collection has no items. // It must be in the same layout used to instantiate the // RemoteViews object. setEmptyView(R.id.stack_view, R.id.empty_view) } // Do additional processing specific to this widget. appWidgetManager.updateAppWidget(appWidgetId, views) } super.onUpdate(context, appWidgetManager, appWidgetIds) }
Java
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter. for (int i = 0; i < appWidgetIds.length; ++i) { // Set up the intent that starts the StackViewService, which // provides the views for this collection. Intent intent = new Intent(context, StackWidgetService.class); // Add the widget ID to the intent extras. intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); // Instantiate the RemoteViews object for the widget layout. RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); // Set up the RemoteViews object to use a RemoteViews adapter. // This adapter connects to a RemoteViewsService through the specified // intent. // This is how you populate the data. views.setRemoteAdapter(R.id.stack_view, intent); // The empty view is displayed when the collection has no items. // It must be in the same layout used to instantiate the RemoteViews // object. views.setEmptyView(R.id.stack_view, R.id.empty_view); // Do additional processing specific to this widget. appWidgetManager.updateAppWidget(appWidgetIds[i], views); } super.onUpdate(context, appWidgetManager, appWidgetIds); }
Duy trì dữ liệu
Như mô tả trên trang này, lớp con RemoteViewsService
cung cấp
RemoteViewsFactory
dùng để điền vào chế độ xem bộ sưu tập từ xa.
Cụ thể, hãy thực hiện các bước sau:
Lớp con
RemoteViewsService
.RemoteViewsService
là dịch vụ mà qua đó bộ chuyển đổi từ xa có thể yêu cầuRemoteViews
.Trong lớp con
RemoteViewsService
, hãy thêm một lớp triển khai giao diệnRemoteViewsFactory
.RemoteViewsFactory
là giao diện của bộ chuyển đổi giữa chế độ xem thu thập từ xa (chẳng hạn nhưListView
,GridView
,StackView
) và dữ liệu cơ bản của chế độ xem đó. Quá trình triển khai của bạn chịu trách nhiệm tạo đối tượngRemoteViews
cho từng mục trong tập dữ liệu. Giao diện này là một trình bao bọc mỏng xung quanhAdapter
.
Bạn không thể duy trì dịch vụ bằng một phiên bản duy nhất hoặc bất kỳ dữ liệu nào trong dịch vụ đó. Không lưu trữ dữ liệu trong RemoteViewsService
trừ phi dữ liệu đó ở dạng tĩnh. Nếu muốn duy trì dữ liệu của tiện ích, phương pháp tốt nhất là sử dụng ContentProvider
có dữ liệu tồn tại ngoài vòng đời của quy trình. Ví dụ: tiện ích cửa hàng tạp hoá có thể lưu trữ trạng thái của từng mặt hàng trong danh sách tạp hoá tại một vị trí cố định, chẳng hạn như cơ sở dữ liệu SQL.
Nội dung chính của quá trình triển khai RemoteViewsService
là RemoteViewsFactory
, được mô tả trong phần sau.
Giao diện RemoteViewsFactory
Lớp tuỳ chỉnh triển khai giao diện RemoteViewsFactory
sẽ cung cấp cho tiện ích dữ liệu về các mục trong bộ sưu tập của lớp đó. Để thực hiện việc này, hệ thống sẽ kết hợp tệp bố cục XML của mục tiện ích với một nguồn dữ liệu. Nguồn dữ liệu này có thể là bất kỳ nội dung nào từ một cơ sở dữ liệu cho đến một mảng đơn giản. Trong mẫu StackWidget
, nguồn dữ liệu là một mảng WidgetItems
. RemoteViewsFactory
hoạt động như một trình chuyển đổi để dán dữ liệu vào chế độ xem bộ sưu tập từ xa.
Hai phương thức quan trọng nhất bạn cần triển khai cho lớp con
RemoteViewsFactory
là
onCreate()
và
getViewAt()
.
Hệ thống gọi onCreate()
trong lần đầu tiên tạo nhà máy.
Đây là nơi bạn thiết lập mọi kết nối hoặc con trỏ đến nguồn dữ liệu. Ví dụ: mẫu StackWidget
sử dụng onCreate()
để khởi tạo một mảng các đối tượng WidgetItem
. Khi tiện ích của bạn đang hoạt động, hệ thống sẽ truy cập các đối tượng này bằng cách sử dụng vị trí chỉ mục trong mảng và hiển thị văn bản chứa các đối tượng đó.
Dưới đây là phần trích dẫn từ phương thức triển khai RemoteViewsFactory
của mẫu StackWidget
, trong đó cho thấy các phần của phương thức onCreate()
:
Kotlin
private const val REMOTE_VIEW_COUNT: Int = 10 class StackRemoteViewsFactory( private val context: Context ) : RemoteViewsService.RemoteViewsFactory { private lateinit var widgetItems: List<WidgetItem> override fun onCreate() { // In onCreate(), set up any connections or cursors to your data // source. Heavy lifting, such as downloading or creating content, // must be deferred to onDataSetChanged() or getViewAt(). Taking // more than 20 seconds on this call results in an ANR. widgetItems = List(REMOTE_VIEW_COUNT) { index -> WidgetItem("$index!") } ... } ... }
Java
class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final int REMOTE_VIEW_COUNT = 10; private List<WidgetItem> widgetItems = new ArrayList<WidgetItem>(); public void onCreate() { // In onCreate(), setup any connections or cursors to your data // source. Heavy lifting, such as downloading or creating content, // must be deferred to onDataSetChanged() or getViewAt(). Taking // more than 20 seconds on this call results in an ANR. for (int i = 0; i < REMOTE_VIEW_COUNT; i++) { widgetItems.add(new WidgetItem(i + "!")); } ... } ...
Phương thức RemoteViewsFactory
getViewAt()
sẽ trả về một đối tượng RemoteViews
tương ứng với dữ liệu tại position
được chỉ định trong tập dữ liệu. Dưới đây là phần trích dẫn từ thao tác triển khai RemoteViewsFactory
của mẫu StackWidget
:
Kotlin
override fun getViewAt(position: Int): RemoteViews { // Construct a remote views item based on the widget item XML file // and set the text based on the position. return RemoteViews(context.packageName, R.layout.widget_item).apply { setTextViewText(R.id.widget_item, widgetItems[position].text) } }
Java
public RemoteViews getViewAt(int position) { // Construct a remote views item based on the widget item XML file // and set the text based on the position. RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_item); views.setTextViewText(R.id.widget_item, widgetItems.get(position).text); return views; }
Thêm hành vi cho từng mục
Các phần trước cho biết cách liên kết dữ liệu của bạn với bộ sưu tập tiện ích. Nhưng nếu bạn muốn thêm hành vi động vào các mục riêng lẻ trong khung hiển thị bộ sưu tập thì sao?
Như đã mô tả trong bài viết Xử lý các sự kiện bằng lớp onUpdate()
, bạn thường sử dụng setOnClickPendingIntent()
để thiết lập hành vi nhấp của một đối tượng, chẳng hạn như để khiến một nút chạy một Activity
. Tuy nhiên, phương pháp này không được phép đối với chế độ xem con trong một mục bộ sưu tập riêng lẻ.
Ví dụ: bạn có thể sử dụng setOnClickPendingIntent()
để thiết lập nút chung
trong tiện ích Gmail dùng để chạy ứng dụng, nhưng không phải trên
các mục danh sách riêng lẻ.
Thay vào đó, để thêm hành vi nhấp vào các mục riêng lẻ trong một bộ sưu tập, hãy sử dụng setOnClickFillInIntent()
. Để làm việc này, bạn cần thiết lập một mẫu ý định đang chờ xử lý cho khung hiển thị bộ sưu tập, sau đó thiết lập ý định điền cho từng mục trong bộ sưu tập thông qua RemoteViewsFactory
.
Phần này sử dụng mẫu StackWidget
để mô tả cách thêm hành vi vào từng mục riêng lẻ. Trong mẫu StackWidget
, nếu người dùng chạm vào thành phần hiển thị trên cùng, thì tiện ích sẽ hiện thông báo Toast
"Thành phần hiển thị được chạm n", trong đó n là chỉ mục (vị trí) của thành phần hiển thị được chạm. Dưới đây là cách hoạt động:
Lớp con
StackWidgetProvider
(một lớp conAppWidgetProvider
) tạo một ý định đang chờ xử lý bằng thao tác tuỳ chỉnh có tên làTOAST_ACTION
.Khi người dùng chạm vào một khung hiển thị, ý định sẽ kích hoạt và truyền phát
TOAST_ACTION
.Việc truyền tin này bị chặn bằng phương thức
onReceive()
của lớpStackWidgetProvider
và tiện ích này sẽ hiển thị thông báoToast
cho khung hiển thị được chạm. Dữ liệu cho các mục của bộ sưu tập đượcRemoteViewsFactory
cung cấp thông quaRemoteViewsService
.
Thiết lập mẫu ý định đang chờ xử lý
StackWidgetProvider
(một lớp con AppWidgetProvider
) thiết lập một ý định đang chờ xử lý. Các mục riêng lẻ của một bộ sưu tập không thể thiết lập ý định đang chờ xử lý của riêng chúng. Thay vào đó, toàn bộ bộ sưu tập sẽ thiết lập một mẫu ý định đang chờ xử lý và các mục riêng lẻ sẽ thiết lập ý định điền sẵn để tạo hành vi duy nhất trên cơ sở từng mục.
Lớp này cũng nhận thông báo truyền tin được gửi khi người dùng chạm vào một khung hiển thị. Trình xử lý sẽ xử lý sự kiện này trong phương thức onReceive()
. Nếu thao tác của ý định là TOAST_ACTION
, tiện ích sẽ hiển thị thông báo Toast
cho khung hiển thị hiện tại.
Kotlin
const val TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION" const val EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM" class StackWidgetProvider : AppWidgetProvider() { ... // Called when the BroadcastReceiver receives an Intent broadcast. // Checks whether the intent's action is TOAST_ACTION. If it is, the // widget displays a Toast message for the current item. override fun onReceive(context: Context, intent: Intent) { val mgr: AppWidgetManager = AppWidgetManager.getInstance(context) if (intent.action == TOAST_ACTION) { val appWidgetId: Int = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) // EXTRA_ITEM represents a custom value provided by the Intent // passed to the setOnClickFillInIntent() method to indicate the // position of the clicked item. See StackRemoteViewsFactory in // Set the fill-in Intent for details. val viewIndex: Int = intent.getIntExtra(EXTRA_ITEM, 0) Toast.makeText(context, "Touched view $viewIndex", Toast.LENGTH_SHORT).show() } super.onReceive(context, intent) } override fun onUpdate( context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray ) { // Update each of the widgets with the remote adapter. appWidgetIds.forEach { appWidgetId -> // Sets up the intent that points to the StackViewService that // provides the views for this collection. val intent = Intent(context, StackWidgetService::class.java).apply { putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) // When intents are compared, the extras are ignored, so embed // the extra sinto the data so that the extras are not ignored. data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME)) } val rv = RemoteViews(context.packageName, R.layout.widget_layout).apply { setRemoteAdapter(R.id.stack_view, intent) // The empty view is displayed when the collection has no items. // It must be a sibling of the collection view. setEmptyView(R.id.stack_view, R.id.empty_view) } // This section makes it possible for items to have individualized // behavior. It does this by setting up a pending intent template. // Individuals items of a collection can't set up their own pending // intents. Instead, the collection as a whole sets up a pending // intent template, and the individual items set a fillInIntent // to create unique behavior on an item-by-item basis. val toastPendingIntent: PendingIntent = Intent( context, StackWidgetProvider::class.java ).run { // Set the action for the intent. // When the user touches a particular view, it has the effect of // broadcasting TOAST_ACTION. action = TOAST_ACTION putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) data = Uri.parse(toUri(Intent.URI_INTENT_SCHEME)) PendingIntent.getBroadcast(context, 0, this, PendingIntent.FLAG_UPDATE_CURRENT) } rv.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent) appWidgetManager.updateAppWidget(appWidgetId, rv) } super.onUpdate(context, appWidgetManager, appWidgetIds) } }
Java
public class StackWidgetProvider extends AppWidgetProvider { public static final String TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION"; public static final String EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM"; ... // Called when the BroadcastReceiver receives an Intent broadcast. // Checks whether the intent's action is TOAST_ACTION. If it is, the // widget displays a Toast message for the current item. @Override public void onReceive(Context context, Intent intent) { AppWidgetManager mgr = AppWidgetManager.getInstance(context); if (intent.getAction().equals(TOAST_ACTION)) { int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); // EXTRA_ITEM represents a custom value provided by the Intent // passed to the setOnClickFillInIntent() method to indicate the // position of the clicked item. See StackRemoteViewsFactory in // Set the fill-in Intent for details. int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0); Toast.makeText(context, "Touched view " + viewIndex, Toast.LENGTH_SHORT).show(); } super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Update each of the widgets with the remote adapter. for (int i = 0; i < appWidgetIds.length; ++i) { // Sets up the intent that points to the StackViewService that // provides the views for this collection. Intent intent = new Intent(context, StackWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); // When intents are compared, the extras are ignored, so embed // the extras into the data so that the extras are not // ignored. intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_layout); rv.setRemoteAdapter(appWidgetIds[i], R.id.stack_view, intent); // The empty view is displayed when the collection has no items. It // must be a sibling of the collection view. rv.setEmptyView(R.id.stack_view, R.id.empty_view); // This section makes it possible for items to have individualized // behavior. It does this by setting up a pending intent template. // Individuals items of a collection can't set up their own pending // intents. Instead, the collection as a whole sets up a pending // intent template, and the individual items set a fillInIntent // to create unique behavior on an item-by-item basis. Intent toastIntent = new Intent(context, StackWidgetProvider.class); // Set the action for the intent. // When the user touches a particular view, it has the effect of // broadcasting TOAST_ACTION. toastIntent.setAction(StackWidgetProvider.TOAST_ACTION); toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]); intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))); PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT); rv.setPendingIntentTemplate(R.id.stack_view, toastPendingIntent); appWidgetManager.updateAppWidget(appWidgetIds[i], rv); } super.onUpdate(context, appWidgetManager, appWidgetIds); } }
Đặt ý định điền
RemoteViewsFactory
của bạn phải đặt ý định điền cho từng mục trong bộ sưu tập. Điều này giúp bạn có thể phân biệt từng thao tác nhấp vào một mục nhất định. Sau đó, ý định điền sẵn được kết hợp với mẫu PendingIntent
để xác định ý định cuối cùng được thực thi khi mục được nhấn vào.
Kotlin
private const val REMOTE_VIEW_COUNT: Int = 10 class StackRemoteViewsFactory( private val context: Context, intent: Intent ) : RemoteViewsService.RemoteViewsFactory { private lateinit var widgetItems: List<WidgetItem> private val appWidgetId: Int = intent.getIntExtra( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID ) override fun onCreate() { // In onCreate(), set up any connections or cursors to your data source. // Heavy lifting, such as downloading or creating content, must be // deferred to onDataSetChanged() or getViewAt(). Taking more than 20 // seconds on this call results in an ANR. widgetItems = List(REMOTE_VIEW_COUNT) { index -> WidgetItem("$index!") } ... } ... override fun getViewAt(position: Int): RemoteViews { // Construct a remote views item based on the widget item XML file // and set the text based on the position. return RemoteViews(context.packageName, R.layout.widget_item).apply { setTextViewText(R.id.widget_item, widgetItems[position].text) // Set a fill-intent to fill in the pending intent template. // that is set on the collection view in StackWidgetProvider. val fillInIntent = Intent().apply { Bundle().also { extras -> extras.putInt(EXTRA_ITEM, position) putExtras(extras) } } // Make it possible to distinguish the individual on-click // action of a given item. setOnClickFillInIntent(R.id.widget_item, fillInIntent) ... } } ... }
Java
public class StackWidgetService extends RemoteViewsService { @Override public RemoteViewsFactory onGetViewFactory(Intent intent) { return new StackRemoteViewsFactory(this.getApplicationContext(), intent); } } class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory { private static final int count = 10; private List<WidgetItem> widgetItems = new ArrayList<WidgetItem>(); private Context context; private int appWidgetId; public StackRemoteViewsFactory(Context context, Intent intent) { this.context = context; appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } // Initialize the data set. public void onCreate() { // In onCreate(), set up any connections or cursors to your data // source. Heavy lifting, such as downloading or creating // content, must be deferred to onDataSetChanged() or // getViewAt(). Taking more than 20 seconds on this call results // in an ANR. for (int i = 0; i < count; i++) { widgetItems.add(new WidgetItem(i + "!")); } ... } // Given the position (index) of a WidgetItem in the array, use the // item's text value in combination with the widget item XML file to // construct a RemoteViews object. public RemoteViews getViewAt(int position) { // Position always ranges from 0 to getCount() - 1. // Construct a RemoteViews item based on the widget item XML // file and set the text based on the position. RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_item); rv.setTextViewText(R.id.widget_item, widgetItems.get(position).text); // Set a fill-intent to fill in the pending // intent template that is set on the collection view in // StackWidgetProvider. Bundle extras = new Bundle(); extras.putInt(StackWidgetProvider.EXTRA_ITEM, position); Intent fillInIntent = new Intent(); fillInIntent.putExtras(extras); // Make it possible to distinguish the individual on-click // action of a given item. rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent); // Return the RemoteViews object. return rv; } ... }
Luôn làm mới dữ liệu về bộ sưu tập
Hình 2 minh hoạ quy trình cập nhật trong một tiện ích sử dụng các bộ sưu tập. Nó cho biết cách mã tiện ích tương tác với RemoteViewsFactory
và cách bạn có thể kích hoạt các bản cập nhật:
Các tiện ích sử dụng bộ sưu tập có thể cung cấp cho người dùng nội dung cập nhật nhất. Ví
dụ: tiện ích Gmail cung cấp cho người dùng thông tin tổng quan nhanh về hộp thư đến của họ. Để làm điều này có thể, hãy kích hoạt RemoteViewsFactory
và khung hiển thị bộ sưu tập để tìm nạp và hiển thị dữ liệu mới.
Để thực hiện việc này, hãy sử dụng AppWidgetManager
để gọi notifyAppWidgetViewDataChanged()
. Lệnh gọi này dẫn đến lệnh gọi lại đến phương thức onDataSetChanged()
của đối tượng RemoteViewsFactory
. Phương thức này cho phép bạn tìm nạp mọi dữ liệu mới.
Bạn có thể thực hiện các thao tác chuyên sâu về xử lý một cách đồng bộ trong lệnh gọi lại onDataSetChanged()
. Bạn được đảm bảo rằng lệnh gọi này được hoàn tất trước khi tìm nạp siêu dữ liệu hoặc dữ liệu khung hiển thị từ RemoteViewsFactory
. Bạn cũng có thể thực hiện các thao tác xử lý chuyên sâu trong phương thức getViewAt()
. Nếu lệnh gọi này mất nhiều thời gian, khung hiển thị đang tải (được chỉ định bởi phương thức getLoadingView()
của đối tượng RemoteViewsFactory
) sẽ hiển thị ở vị trí tương ứng của khung hiển thị bộ sưu tập cho đến khi trả về.
Sử dụng RemoteCollectionItems để truyền trực tiếp tập hợp
Android 12 (API cấp 31) thêm phương thức setRemoteAdapter(int viewId,
RemoteViews.RemoteCollectionItems
items)
, phương thức này cho phép ứng dụng của bạn truyền trực tiếp bộ sưu tập khi điền sẵn khung hiển thị bộ sưu tập. Nếu đặt bộ chuyển đổi bằng phương thức này, bạn không cần triển khai RemoteViewsFactory
và không cần gọi notifyAppWidgetViewDataChanged()
.
Phương pháp này không chỉ giúp bạn điền sẵn bộ chuyển đổi dễ dàng hơn, mà còn giúp loại bỏ độ trễ khi điền các mục mới khi người dùng cuộn xuống danh sách để hiển thị một mục mới. Phương pháp cài đặt bộ chuyển đổi này sẽ được ưu tiên, miễn là tập hợp các mục trong bộ sưu tập của bạn tương đối nhỏ. Tuy nhiên, chẳng hạn như phương pháp này sẽ không hiệu quả nếu bộ sưu tập của bạn chứa nhiều Bitmaps
được truyền đến setImageViewBitmap
.
Nếu bộ sưu tập không sử dụng tập hợp bố cục cố định (nghĩa là nếu một số mục chỉ thỉnh thoảng xuất hiện), hãy sử dụng setViewTypeCount
để chỉ định số lượng bố cục riêng biệt tối đa mà bộ sưu tập có thể chứa. Điều này cho phép sử dụng lại bộ chuyển đổi trên các bản cập nhật cho tiện ích ứng dụng.
Dưới đây là ví dụ về cách triển khai các tập hợp RemoteViews
được đơn giản hoá.
Kotlin
val itemLayouts = listOf( R.layout.item_type_1, R.layout.item_type_2, ... ) remoteView.setRemoteAdapter( R.id.list_view, RemoteViews.RemoteCollectionItems.Builder() .addItem(/* id= */ ID_1, RemoteViews(context.packageName, R.layout.item_type_1)) .addItem(/* id= */ ID_2, RemoteViews(context.packageName, R.layout.item_type_2)) ... .setViewTypeCount(itemLayouts.count()) .build() )
Java
List<Integer> itemLayouts = Arrays.asList( R.layout.item_type_1, R.layout.item_type_2, ... ); remoteView.setRemoteAdapter( R.id.list_view, new RemoteViews.RemoteCollectionItems.Builder() .addItem(/* id= */ ID_1, new RemoteViews(context.getPackageName(), R.layout.item_type_1)) .addItem(/* id= */ ID_2, new RemoteViews(context.getPackageName(), R.layout.item_type_2)) ... .setViewTypeCount(itemLayouts.size()) .build() );