Android Widget桌面小部件是可以在主頁上顯示並頻繁更新的視圖。作為視圖,部件的觀感通過布局xml文件來定義。對於部件,除了視圖的布局,還需要定義部件視圖將需要在屏幕上占用多大空間。
部件視圖還包括一對Java類,他們負責初始化視圖並頻繁更新它,這些Java類負責在主屏幕上管理部件的生命周期。當將部件拖到屏幕上,以及將部件拖到回收站進行卸載時,這些類進行相應。
下面通過一個倫敦奧運會倒計時的簡單Widget例子來說明如何創建一個桌面小部件。
1、定義一個AppWidgetProviderInfo,在/res/xml/widget.xml
- <?xml version="1.0" encoding="utf-8"?>
- <appwidget-provider
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:minWidth="50dip"
- android:minHeight="50dip"
- android:updatePeriodMillis="10000"
- android:initialLayout="@layout/main"
- >
- </appwidget-provider>
2、為AppWidget指定樣式和布局:main.xml
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="@drawable/icon"
- >
- <TextView
- android:id="@+id/Olympic"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- android:textSize="12px"
- android:textColor="#ff00ff"
- />
- </LinearLayout>
3、實現AppWidgetProvider類
- public class WidgetDemo extends AppWidgetProvider {
- @Override
- public void onUpdate(Context context, AppWidgetManager appWidgetManager,
- int[] appWidgetIds) {
- // TODO Auto-generated method stub
- Timer timer = new Timer();
- timer.scheduleAtFixedRate(new MyTime(context,appWidgetManager), 1, 60000);
- super.onUpdate(context, appWidgetManager, appWidgetIds);
- }
- //定時任務類
- private class MyTime extends TimerTask{
- RemoteViews remoteViews;
- AppWidgetManager appWidgetManager;
- ComponentName thisWidget;
-
- public MyTime(Context context,AppWidgetManager appWidgetManager){
- this.appWidgetManager = appWidgetManager;
- remoteViews = new RemoteViews(context.getPackageName(),R.layout.main);
-
- thisWidget = new ComponentName(context,WidgetDemo.class);
- }
- //定時任務內容
- public void run() {
- Date date = new Date();
- Calendar calendar = new GregorianCalendar(2012,06,28);
- long days = ((calendar.getTimeInMillis()-date.getTime())/(1000*60*60*24));
- remoteViews.setTextViewText(R.id.Olympic, "距離倫敦奧運會還有" + days+"天");
- //更新Widget內容
- appWidgetManager.updateAppWidget(thisWidget, remoteViews);
- }
- }
- }
4、在AndroidManifest.xml中注冊:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.test.widget"
- android:versionCode="1"
- android:versionName="1.0">
-
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <receiver android:name=".WidgetDemo"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
- </intent-filter>
- <meta-data android:name="android.appwidget.provider"
- android:resource="@xml/widget"
- />
- </receiver>
- </application>
- </manifest>
運行程序,長按桌面在談出的選項中選擇窗口小部件,結果如圖:
然後選擇olympic widget,結果如圖所示:
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11