Sử dụng tiện ích bộ sưu tập

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ư dưới dạng bộ sưu tập hình ảnh từ ứng dụng thư viện, bài viết từ ứng dụng tin tức, hoặc tin nhắn từ một ứng dụng liên lạc. Các tiện ích thu thập thường tập trung vào 2 hoạt động sử dụng trường hợp: duyệt qua bộ sưu tập và mở một phần tử của bộ sưu tập vào 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 nội dung Google Workspace. Tiện ích này sẽ hiển thị bằng cách sử dụng một trong các kiểu khung hiển thị sau, được gọi là bộ sưu tập lượt xem:

ListView
Một thành phần hiển thị các mục trong một danh sách cuộn theo chiều dọc.
GridView
Một thành phần hiển thị các mục trong một lưới cuộn hai chiều.
StackView
Một thẻ xếp chồng chế độ xem—giống như một trò chơi rolodex—nơi người dùng có thể xoay mặt trước lên hoặc xuống để xem thẻ trước đó hoặc thẻ tiếp theo tương ứng.
AdapterViewFlipper
An đơn giản dựa trên bộ chuyển đổi ViewAnimator tạo hiệu ứng động từ 2 chế độ xem trở lên. Mỗi lần chỉ có một trẻ xuất hiện.

Vì các chế độ xem bộ sưu tập này hiển thị 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 người dùng vào dữ liệu của họ. 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 hỗ trợ bởi các bộ chuyển đổi, nên khung Android phải có cấu trúc bổ sung để hỗ trợ việc sử dụng chúng trong tiện ích. Theo bối cảnh của một tiện ích, Adapter sẽ đượ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 cho một 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 vào chế độ xem bộ sưu tập trong tiện ích của bạn, hãy triển khai RemoteViewsServiceRemoteViewsFactory

RemoteViewsService là dịch vụ cho phép yêu cầu bộ chuyển đổi từ xa Đối tượng RemoteViews. RemoteViewsFactory là một giao diện cho trình chuyển đổi giữa một chế độ xem bộ sưu tập, chẳng hạn như ListView, GridViewStackView – và dữ liệu cơ bản cho chế độ xem đó. Từ StackWidget mẫu, đây là một ví dụ về mã nguyên mẫu để triển khai dịch vụ này và giao diện:

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 mã trong phần này cũng được lấy từ StackWidget mẫu:

Hình 1. 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ị bằng 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 theo chiều dọc từ khung hiển thị trên cùng trong tiện ích để hiển thị hoặc chế độ xem trước đó. Đây là hành vi StackView tích hợp sẵn.

  • Khi không có bất kỳ sự tương tác nào của người dùng, tiện ích này sẽ tự động chuyển qua chế độ xem theo trình tự, như trình chiếu. Điều này là do chế độ cài đặt android:autoAdvanceViewId="@id/stack_view" trong res/xml/stackwidgetinfo.xml. Cài đặt này áp dụng cho ID chế độ xem, trong trường hợp này là mã nhận dạng khung hiển thị của khung hiển thị ngăn xếp.

  • Nếu người dùng chạm vào chế độ xem trên cùng, tiện ích sẽ hiển thị Toast thông báo "Chế độ xem đã chạm n," ở đâu n là chỉ mục (vị trí) của thành phần 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 items.

Triển khai tiện ích với bộ sưu tập

Để triển khai tiện ích với các bộ sưu tập, hãy làm theo quy trình để triển khai bất kỳ , sau đây 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 được liệt kê trong Khai báo tiện ích trong tệp kê khai, bạn cần tạo điều kiện cho các tiện ích có để 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 phương thức trong tệp kê khai của bạn bằng 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 một chế độ xem bộ sưu tập, mục nhập tệp kê khai sẽ 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 chế độ xem bộ sưu tập: ListView, GridView, StackView hoặc AdapterViewFlipper. Đây là tệp widget_layout.xml cho StackWidget mẫu:

<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 các khung hiển thị trống phải là các khung hiển thị đồ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 bố cục khác tệp 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ưu tập sách. Mẫu StackWidget có chỉ một tệp bố cục mục, widget_item.xml, vì tất cả các mục sử dụng cùng một của bạn.

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 thường mất onUpdate(). Sự khác biệt lớn trong việc triển khai của bạn đối với onUpdate() khi tạo một 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 của bạn RemoteViewsFactory và tiện ích này có thể phân phát dữ liệu thích hợp. Khi gọi phương thức này, hãy chuyển một ý định trỏ đến phương thức triển khai của bạn 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 onUpdate() để đặt RemoteViewsService làm bộ chuyển đổi từ xa cho bộ sưu tậ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 sẵn chế độ xem bộ sưu tập từ xa.

Cụ thể, hãy thực hiện các bước sau:

  1. Lớp con RemoteViewsService. RemoteViewsService là dịch vụ thông qua mà bộ chuyển đổi từ xa có thể yêu cầu RemoteViews.

  2. Trong lớp con RemoteViewsService, hãy thêm một lớp triển khai phương thức Giao diện RemoteViewsFactory. RemoteViewsFactory là một giao diện cho bộ chuyển đổi giữa chế độ xem bộ sưu tập từ xa—chẳng hạn như ListView, GridView, StackView – và dữ liệu cơ bản cho chế độ xem đó. Thông tin Quá trình triển khai chịu trách nhiệm tạo đối tượng RemoteViews cho mỗi mục trong tập dữ liệu. Giao diện này là một trình bao bọc mỏng xung quanh Adapter.

Bạn không được dựa vào một phiên bản dịch vụ duy nhất hoặc bất kỳ dữ liệu nào trong dịch vụ đó để tồn tại lâu dài. Không lưu trữ dữ liệu trong RemoteViewsService trừ phi dữ liệu đó ở dạng tĩnh. Nếu bạn muốn dữ liệu tiện ích của mình tồn tại thì cách tốt nhất là sử dụng ContentProvider có dữ liệu vẫn 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 việc triển khai RemoteViewsServiceRemoteViewsFactory, được mô tả trong phần sau.

Giao diện RemoteViewsFactory

Lớp tuỳ chỉnh triển khai giao diện RemoteViewsFactory mang lại tiện ích có dữ liệu về các mục trong bộ sưu tập của tiện ích đó. Để thực hiện việc này, 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 này của dữ liệu 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 StackWidget mẫu, nguồn dữ liệu là một mảng WidgetItems. RemoteViewsFactory có chức năng như một bộ chuyển đổi để gắn dữ liệu vào chế độ xem bộ sưu tập từ xa.

Hai phương pháp quan trọng nhất mà bạn cần triển khai cho Lớp con RemoteViewsFactoryonCreate()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. Cho Ví dụ: mẫu StackWidget sử dụng onCreate() để khởi tạo một mảng Đối tượng WidgetItem. Khi tiện ích của bạn hoạt động, hệ thống sẽ truy cập vào bằng cách sử dụng vị trí chỉ mục trong mảng và hiển thị văn bản mà chúng chứa.

Dưới đây là một phần trích dẫn từ RemoteViewsFactory của mẫu StackWidget phương thức triển khai 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() trả về đối tượng RemoteViews tương ứng với dữ liệu tại position được chỉ định trong tập dữ liệu. Sau đây là phần trích dẫn từ quá trình 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 chế độ xem bộ sưu tập không?

Như mô tả trong bài viết Xử lý sự kiện bằng onUpdate() class, 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ư làm cho một nút khởi chạy Activity. Nhưng không được phép sử dụng phương pháp này đố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 chạy ứng dụng nhưng không chạy trên các mục danh sách riêng lẻ.

Thay vào đó, để thêm hành vi nhấp vào từng mục 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 chế độ xem bộ sưu tập của bạn rồi thiết lập ý định điền cho từng mục trong thu thập qua RemoteViewsFactory của bạn.

Phần này sử dụng mẫu StackWidget để mô tả cách thêm hành vi vào các 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, tiện ích sẽ hiển thị thông báo Toast "Chế độ xem đã chạm n," trong đó n là chỉ mục (vị trí) của chế độ xem được chạm. Dưới đây là cách hoạt động:

  • StackWidgetProvider—một AppWidgetProvider lớp con – tạo một ý định đang chờ xử lý thông qua một thao tác tuỳ chỉnh được gọi 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 tin TOAST_ACTION.

  • Quá trình truyền tin này bị chặn bởi lớp StackWidgetProvider onReceive() và tiện ích này sẽ hiển thị thông báo Toast cho chế độ xem được chạm. Dữ liệu cho các mục của bộ sưu tập được cung cấp bởi RemoteViewsFactory thông qua RemoteViewsService.

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ý. Bạn không thể thiết lập các mục riêng lẻ trong một bộ sưu tập ý định đang chờ xử lý riêng. Thay vào đó, toàn bộ bộ sưu tập sẽ thiết lập một ý định đang chờ xử lý và các mục riêng lẻ thiết lập ý định điền để tạo hành vi theo từng mặt hàng.

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 chế độ xem. Trình xử lý sẽ xử lý sự kiện này trong phương thức onReceive(). Nếu ý định là là TOAST_ACTION, tiện ích này sẽ hiển thị thông báo Toast cho hành động hiện tại chế độ xem.

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 hành động nhấp chuột của một mặt hàng nhất định. Sau đó, ý định điề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. Chiến dịch này cho thấy 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ập nhật:

Hình 2. Tương tác với RemoteViewsFactory trong quá trình 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. Cho 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ọ. Để thực hiện việc 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 đối tượng RemoteViewsFactory của bạn onDataSetChanged() 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 cuộc gọi này đã hoàn tất trước khi siêu dữ liệu hoặc dữ liệu khung hiển thị được tìm nạp từ RemoteViewsFactory. Bạn cũng có thể thực hiện các thao tác xử lý chuyên sâu trong 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 RemoteViewsFactory của đối tượng getLoadingView() phương thức—được 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 setRemoteAdapter(int viewId, RemoteViews.RemoteCollectionItems items) cho phép ứng dụng của bạn trực tiếp truyền tập hợp khi điền sẵn một chế độ xem 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à bạn không cần gọi notifyAppWidgetViewDataChanged()

Ngoài việc giúp điền sẵn bộ chuyển đổi dễ dàng hơn, phương pháp này cũng loại bỏ độ trễ để đ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 thiết lập bộ chuyển đổi này sẽ được ưu tiên miễn là tập hợp các mục bộ sưu tập tương đối nhỏ. Tuy nhiên, ví dụ: không hoạt động tốt nếu bộ sưu tập của bạn chứa nhiều Bitmaps đang được đượ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, tức là nếu một số các mục chỉ thỉnh thoảng xuất hiện. Hãy sử dụng setViewTypeCount để chỉ định số lượng tối đa bố cục duy nhất mà bộ sưu tập có thể chứa. Điều này cho phép bộ chuyển đổi được sử dụng lạ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()
);