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ư 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ừ ứng dụng liên lạc. Tiện ích bộ sưu tập thường tập trung vào 2 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 để xem chi tiết. Tiện ích tập hợ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 hỗ trợ bởi dữ liệu từ xa, chẳng hạn như 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 gọi là khung hiển thị bộ sưu tập):

ListView
Khung hiển thị cho thấy các mục trong danh sách cuộn theo chiều dọc.
GridView
Khung hiển thị hiển thị các mục trong lưới cuộn hai chiều.
StackView
Chế độ xem thẻ xếp chồng (tương tự như chế độ xem rolodex) nơi người dùng có thể xoay thẻ trước lên hoặc xuống để xem thẻ trước hoặc thẻ tiếp theo.
AdapterViewFlipper
Một ViewAnimator đơn giản hỗ trợ bộ chuyển đổi có thể tạo ảnh động giữa hai hoặc nhiều khung hiển thị. Mỗi lần chỉ hiển thị một trẻ.

Vì các khung hiển thị bộ sưu tập này hiển thị các tập hợp được dữ liệu từ xa hỗ trợ, nên các khung hiển thị này sẽ sử dụng Adapter để liên kết giao diện người dùng với dữ liệu của mình. Adapter liên kết từng mục từ một tập dữ liệu với từng đối tượng View.

Vì các khung hiển thị bộ sưu tập này được bộ chuyển đổi hỗ trợ, nên khung Android phải bao gồm cấu trúc bổ sung để hỗ trợ việc sử dụng các khung hiển thị đó trong các tiện ích. Trong ngữ cảnh của một tiện ích, Adapter được thay thế bằng một RemoteViewsFactory, 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ụ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 một khung hiển thị bộ sưu tập vào tiện ích, hãy triển khai RemoteViewsServiceRemoteViewsFactory.

RemoteViewsService là một dịch vụ cho phép bộ chuyển đổi từ xa yêu cầu đối tượng RemoteViews. RemoteViewsFactory là giao diện cho trình chuyển đổi giữa một khung hiển thị bộ sưu tập (chẳng hạn như ListView, GridViewStackView) và dữ liệu cơ bản của khung hiển thị đó. Trong mẫu StackWidget, 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 phần trích dẫn mã trong phần này cũng được lấy từ mẫu StackWidget:

Hình 1. StackWidget.

Mẫu này bao gồm một ngăn xếp gồm 10 thành phần hiển thị hiển thị 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 trong tiện ích theo chiều dọc để cho thấy khung hiển thị tiếp theo hoặc trước đó. Đây là hành vi StackView được tích hợp sẵn.

  • Nếu không có bất kỳ tương tác nào của người dùng, tiện ích này sẽ tự động chuyển qua các chế độ xem theo trình tự, chẳng hạn như bản trình chiếu. Điều này là do chế độ cài đặt android:autoAdvanceViewId="@id/stack_view" trong tệp res/xml/stackwidgetinfo.xml. Chế độ cài đặt này áp dụng cho mã khung hiển thị, mà 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 chế độ xem trên cùng, tiện ích sẽ hiển thị Toast thông báo "Chế độ xem được chạm n", trong đó n của chế độ xem được chạm là Để thảo luận thêm về cách triển khai các 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 khung hiển thị bộ sưu tập vào bố cục tiện ích và sửa đổi lớp con AppWidgetProvider của bạn.

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 phần Khai báo tiện ích trong tệp kê khai, bạn cần tạo điều kiện để các tiện ích có bộ sưu tập có thể liên kết với RemoteViewsService. Bạn có thể 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 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 của bạn là tệp này phải bao gồm một trong các chế độ xem bộ sưu tập: ListView, GridView, StackView hoặc AdapterViewFlipper. Dưới đâ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à đồ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ưu tập 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 thường nằm trong onUpdate(). Điểm khác biệt chính trong cách triển khai onUpdate() khi tạo tiện ích bằng các bộ sưu tập là bạn phải gọi setRemoteAdapter(). Thông tin này cho khung hiển thị bộ sưu tập biết nơi để lấy dữ liệu. Sau đó, RemoteViewsService có thể trả về cách 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 truyền một ý định trỏ đến cách triển khai RemoteViewsService của bạn 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 việc thu thậ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 khung hiển thị tập hợ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ụ mà thông qua đó 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 giao diện RemoteViewsFactory. RemoteViewsFactory là giao diện cho một bộ chuyển đổi giữa khung hiển thị tập hợp từ xa (chẳng hạn như ListView, GridView, StackView) và dữ liệu cơ bản của khung hiển thị đó. Phương thức triển khai của bạn chịu trách nhiệm tạo một đố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 thể dựa vào một thực thể của dịch vụ hoặc bất kỳ dữ liệu nào trong đó để duy trì. 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 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 vẫn tồn tại ngoài vòng đời xử lý. 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 hàng tạp hoá ở 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 cung cấp tiện ích chứa dữ liệu cho các mục trong bộ sưu tập. Để làm việc này, công 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 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 khung hiển thị tập hợp từ xa.

Hai phương thức 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() khi tạo nhà máy lần đầu tiên. Đâ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 của mình. Ví dụ: mẫu StackWidget sử dụng onCreate() để khởi tạo một mảng gồm các đối tượng WidgetItem. Khi tiện ích của bạn hoạt động, hệ thống sẽ truy cập vào các đối tượng này bằng cách sử dụng vị trí chỉ mục của chúng trong mảng và hiển thị văn bản chứa các đối tượng đó.

Dưới đây là một phần trích dẫn từ quá trình 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() 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ừ cách 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ên cho biết cách liên kết dữ liệu với bộ sưu tập tiện ích của bạn. 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 thì sao?

Như mô tả trong phần Xử lý các sự kiện bằng lớp onUpdate(), bạn thường dùng setOnClickPendingIntent() để đặt hành vi nhấp của một đối tượng, chẳng hạn như tạo một nút để chạy một Activity. Tuy nhiên, phương pháp này không áp dụng cho các khung hiển thị 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 giúp khởi 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 từng mục trong một bộ sưu tập, hãy sử dụng setOnClickFillInIntent(). Quá trình này đòi hỏi bạn phải thiết lập một mẫu ý định đang chờ xử lý cho khung hiển thị bộ sưu tập, sau đó đặt ý đị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 các mục riêng lẻ. Trong mẫu StackWidget, 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ị thông báo Toast "Chạm vào khung hiển thị n", trong đó n là chỉ mục (vị trí) của khung hiển thị được chạm. Dưới đây là cách hoạt động:

  • StackWidgetProvider—một lớp con AppWidgetProvider—tạo một ý định đang chờ xử lý bằng một 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à sẽ truyền TOAST_ACTION.

  • Tin truyền này bị chặn bằng phương thức onReceive() của lớp StackWidgetProvider và tiện ích sẽ hiển thị thông báo Toast cho thành phần hiển thị đã chạm. Dữ liệu cho các mục trong bộ sưu tập do RemoteViewsFactory cung cấp 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ý. 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ý riêng. Thay vào đó, về tổng thể, 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ẽ đặt ý định điề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 thành phần hiển thị. Hàm này 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. Nhờ vậy, bạn có thể phân biệt từng thao tác khi nhấp của một mục nhất định. Sau đó, ý định điền sẽ đượ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.

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 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. Mẫu này 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 bản 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. 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ọ. Để có thể làm việc này, 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 một 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 đồng bộ các thao tác cần xử lý chuyên sâu trong lệnh gọi lại onDataSetChanged(). Bạn phải đảm bảo rằng lệnh gọi này sẽ hoàn tất trước khi tìm nạp siêu dữ liệu hoặc dữ liệu chế độ xem 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, thì khung hiển thị đang tải (được chỉ định bằng 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 được trả về.

Sử dụng RemoteCollectionItems để truyền trực tiếp bộ sưu tập

Android 12 (API cấp 31) thêm phương thức setRemoteAdapter(int viewId, RemoteViews.RemoteCollectionItems items), cho phép ứng dụng của bạn truyền trực tiếp một bộ sưu tập khi điền sẵn khung hiển thị bộ sưu tập. Nếu thiết lập 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().

Ngoài việc giúp điền bộ chuyển đổi dễ dàng hơn, phương pháp này còn 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ục mới. Phương pháp đặt bộ chuyển đổi này đượ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, ví dụ: 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 một tập hợp bố cục không đổi – tức là nếu một số mục 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 này 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()
);