Android Widget简单应用之奥运会倒计时
Android Widget简单应用之奥运会倒计时
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>
- <?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>
- 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);
- }
- }
- }
- <?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.bkjia.com/topicnews.aspx?tid=11
评论暂时关闭