Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Widget 小部件(四):用 ListView、GridView、StackView、ViewFlipper 打造集合型 Widget

編輯:關於 Android 程式設計

官方文件對 RemoteViews 能支援的內容有明確限制。它只認得以下幾種布局:FrameLayout、、RelativeLayout;而可用的控件則是 AnalogClock、Button、Chronometer、ImageButton、ImageView、ProgressBar、TextView、ViewFlipper、ListView、GridView、StackView、AdapterViewFlipper。更關鍵的是——這些類別的「子類」都不被支援,所以你不能把自訂的 CustomListView 塞進 Widget 裡。

本文示範如何用 ListView、GridView、StackView、ViewFlipper 這四種展示元件來製作 App Widget,其中前三種屬於「集合型 Widget」,需要搭配 RemoteViewsService 提供資料。

一、manifest 宣告

<receiver android:name="com.stone.receiver.WidgetSetProvider">
    <intent-filter>
    </intent-filter>
    <meta-data android:name="android.appwidget.provider"
        android:resource="@xml/set_widget_provider"/>
</receiver>

二、Widget 描述檔 set_widget_provider.xml

這裡整理幾個實務上很常被搞混的屬性。尺寸計算公式為 (70*n) - 30,n 是佔幾格,下面範例是 4x4。

minResizeWidth / minResizeHeight:可被調整的最小寬高,若數值大於 minWidth、minHeight 則會被忽略。

label / icon:使用者在選擇 Widget 時看到的標籤與圖示。

updatePeriodMillis:更新間隔(毫秒)。注意系統對此有下限限制,設太小不會真的那麼頻繁更新。

previewImage:選擇 Widget 時預覽用的圖像,3.0 以上才支援。

resizeMode:調整尺寸的模式。

configure:若需要在 Widget 真正建立前先跳出一個設定 Activity,在此填入該 Activity 的完整類名。

widgetCategory:可放置的位置,「keyguard」為鎖屏,「home_screen」為桌面。

autoAdvanceViewId:與集合型 Widget 搭配使用,指定自動推進的 item 容器。實測目前主要對 StackView 有效,會每隔一段時間自動切到下一個。

集合型 Widget 是 3.0 之後才有的,包含 ListView、GridView、StackView、AdapterViewFlipper;而 ViewFlipper 並不屬於集合型,這點在後面的程式碼裡會造成明顯差異。

三、Widget 的布局檔 collections_view_widget.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <Button android:id="@+id/btn_listview"
            android:layout_width="0dp" android:layout_height="wrap_content"
            android:layout_weight="1" android:text="listview" />
        <Button android:id="@+id/btn_gridview"
            android:layout_width="0dp" android:layout_height="wrap_content"
            android:layout_weight="1" android:text="gridview" />
        <Button android:id="@+id/btn_stackview"
            android:layout_width="0dp" android:layout_height="wrap_content"
            android:layout_weight="1" android:text="stackview" />
        <Button android:id="@+id/btn_viewflipper"
            android:layout_width="0dp" android:layout_height="wrap_content"
            android:layout_weight="1" android:text="viewflipper" />
    </LinearLayout>

    <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#80000000" >

        <ListView android:id="@+id/listview"
            android:layout_width="fill_parent" android:layout_height="fill_parent" />

        <GridView android:id="@+id/gridview"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:numColumns="2" android:visibility="gone" />

        <StackView android:id="@+id/stackview"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:visibility="gone" />

        <ViewFlipper android:id="@+id/viewflipper"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:autoStart="true" android:flipInterval="2000"
            android:visibility="gone" >
            <!-- autoStart=true 等同 startFlipping(),flipInterval 決定停留時間 -->
            <ImageView android:id="@+id/iv1"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:background="@drawable/a1" />
            <ImageView android:id="@+id/iv2"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:background="@drawable/a2" />
            <ImageView android:id="@+id/iv3"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:background="@drawable/a3" />
            <ImageView android:id="@+id/iv4"
                android:layout_width="fill_parent" android:layout_height="fill_parent"
                android:background="@drawable/a4" />
        </ViewFlipper>

        <TextView android:id="@+id/tv_empty"
            android:layout_width="fill_parent" android:layout_height="fill_parent"
            android:gravity="center" android:text="Empty List"
            android:visibility="gone" />
    </FrameLayout>
</LinearLayout>

四、資料來源:繼承 RemoteViewsService

集合型 Widget 的資料必須由一個繼承 RemoteViewsService 的 Service 提供,並在 onGetViewFactory() 中回傳自訂的 RemoteViewsFactory。

package com.stone.service;

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import com.stone.R;
import com.stone.receiver.WidgetSetProvider;

public class WidgetSetService extends RemoteViewsService {

    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new WidgetFactory(this.getApplicationContext(), intent);
    }

    public class WidgetFactory implements RemoteViewsService.RemoteViewsFactory {
        private static final int mCount = 10;
        private Context mContext;
        private List<String> mWidgetItems = new ArrayList<String>();

        public WidgetFactory(Context context, Intent intent) {
            mContext = context;
        }

        @Override
        public void onCreate() {
            for (int i = 0; i < mCount; i++) {
                mWidgetItems.add("item:" + i + "!");
            }
        }

        @Override
        public void onDataSetChanged() {
            // 呼叫 notifyAppWidgetViewDataChanged 時會回調這裡
        }

        @Override
        public void onDestroy() {
            mWidgetItems.clear();
        }

        @Override
        public int getCount() {
            return mCount;
        }

        @Override
        public RemoteViews getViewAt(int position) {
            RemoteViews views = new RemoteViews(mContext.getPackageName(),
                    android.R.layout.simple_list_item_1);
            views.setTextViewText(android.R.id.text1, "item:" + position);

            Bundle extras = new Bundle();
            extras.putInt(WidgetSetProvider.EXTRA_ITEM, position);
            Intent fillInIntent = new Intent();
            fillInIntent.putExtras(extras);

            // item 的點擊:把 fillInIntent 併入 provider 設定的 pendingIntent 模板
            views.setOnClickFillInIntent(android.R.id.text1, fillInIntent);
            return views;
        }

        @Override
        public RemoteViews getLoadingView() {
            // 回傳 null 使用預設的「載入中」樣式
            return null;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }
    }
}

五、WidgetProvider 的實作

package com.stone.receiver;

import com.stone.R;
import com.stone.service.WidgetSetService;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RemoteViews;

public class WidgetSetProvider extends AppWidgetProvider {
    public final static String CLICK_ACTION = "com.stone.action.clickset";
    public final static String CLICK_ITEM_ACTION = "com.stone.action.clickset.item";
    public final static String EXTRA_ITEM = "extra_item";

    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if (TextUtils.equals(CLICK_ACTION, intent.getAction())) {
            int extraType = intent.getIntExtra("view_tag", 0);
            if (extraType > 0) {
                switch (extraType) {
                    case 1:
                        updateWidget(context, R.id.listview, R.id.gridview, R.id.stackview, R.id.viewflipper);
                        break;
                    case 2:
                        updateWidget(context, R.id.gridview, R.id.listview, R.id.stackview, R.id.viewflipper);
                        break;
                    case 3:
                        updateWidget(context, R.id.stackview, R.id.gridview, R.id.listview, R.id.viewflipper);
                        break;
                    case 4:
                        updateWidget(context, R.id.viewflipper, R.id.gridview, R.id.stackview, R.id.listview);
                        break;
                }
            }
        } else if (TextUtils.equals(CLICK_ITEM_ACTION, intent.getAction())) {
            Bundle extras = intent.getExtras();
            int position = extras.getInt(WidgetSetProvider.EXTRA_ITEM, -1);
            if (position != -1) {
                // 在這裡處理被點擊的 item
            }
        }
    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.collections_view_widget);

        views.setOnClickPendingIntent(R.id.btn_listview,
                PendingIntent.getBroadcast(context, 101,
                        new Intent(CLICK_ACTION).putExtra("view_tag", 1), 0));
        views.setOnClickPendingIntent(R.id.btn_gridview,
                PendingIntent.getBroadcast(context, 102,
                        new Intent(CLICK_ACTION).putExtra("view_tag", 2), 0));
        views.setOnClickPendingIntent(R.id.btn_stackview,
                PendingIntent.getBroadcast(context, 103,
                        new Intent(CLICK_ACTION).putExtra("view_tag", 3), 0));
        views.setOnClickPendingIntent(R.id.btn_viewflipper,
                PendingIntent.getBroadcast(context, 104,
                        new Intent(CLICK_ACTION).putExtra("view_tag", 4), 0));

        appWidgetManager.updateAppWidget(appWidgetIds, views);
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }

    private void updateWidget(Context context, int visible, int gone1, int gone2, int gone3) {
        // RemoteViews 是用來操作跨進程的 View
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.collections_view_widget);
        views.setViewVisibility(visible, View.VISIBLE);
        views.setViewVisibility(gone1, View.GONE);
        views.setViewVisibility(gone2, View.GONE);
        views.setViewVisibility(gone3, View.GONE);

        if (visible != R.id.viewflipper) {
            // ViewFlipper 並非繼承自 AbsListView 或 AdapterViewAnimator,不能用 setRemoteAdapter
            Intent intent = new Intent(context, WidgetSetService.class);
            views.setRemoteAdapter(visible, intent);      // 設定集合的 adapter
            views.setEmptyView(visible, R.id.tv_empty);   // 集合為空時顯示的 view

            Intent toIntent = new Intent(CLICK_ITEM_ACTION);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 200, toIntent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            // setPendingIntentTemplate 設定模板,再由 setOnClickFillInIntent 填入實際資料
            views.setPendingIntentTemplate(visible, pendingIntent);
        }

        AppWidgetManager am = AppWidgetManager.getInstance(context);
        int[] appWidgetIds = am.getAppWidgetIds(new ComponentName(context, WidgetSetProvider.class));
        for (int i = 0; i < appWidgetIds.length; i++) {
            am.updateAppWidget(appWidgetIds[i], views);
        }
    }
}

這裡最關鍵的設計是「模板 + 填充」的兩段式點擊處理:先用 setPendingIntentTemplate() 綁定一個統一的 PendingIntent 模板,再由每個 item 透過 setOnClickFillInIntent() 補上自己的 position,點擊時兩者會合併成完整的 Intent 送回 Provider。這樣就不必為每一個 item 各建一個 PendingIntent,也不會撞到 PendingIntent 數量上限。

反觀 ViewFlipper,因為它不是集合型元件,RemoteViews 並未提供對應的設定方式,所以輪播效果只能在布局檔裡用 autoStart 與 flipInterval 事先寫死;至於「目前顯示到第幾張」這種細粒度的事件,也難以精準掌握,實務上只能對整個容器掛一個統一的 setPendingIntent。

六、執行結果

Widget 的生命週期回調依序為 onEnabled → onUpdate →(刪除時)onDeleted → onDisabled,其中 onUpdate 是最主要的工作入口。

點擊 stackview 後的效果如下,四種展示模式共用同一份布局,透過 visibility 切換:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved