Android进阶之widget桌面
博客出自:http://blog.csdn.net/liuxian13183,转载注明出处!
All Rights Reserved !
Widget,就是应用程序的部分功能在桌面的快速打开方式。
关于Widget的使用,实战操作
1、写好widget的布局文件,想怎么布局就怎么写
2、在xml目录下写好资源文件
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="80dip"
android:minHeight="80dip"
android:updatePeriodMillis="43200000"
android:initialLayout="@layout/widget_layout2x2"
android:configure="">
</appwidget-provider>3、主配置文件中声明
<receiver android:name="Widget名字" android:label="@string/app_name02"> <meta-data android:name="android.appwidget.provider" android:resource="@xml/资源名" /> <intent-filter> <action android:name="过滤器" /> </intent-filter> </receiver>
4、类名 extends AppWidgetProvider
private RemoteViews remoteViews;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
super.onReceive(context, intent);
String action = intent.getAction();
if (action.equals("过滤器名")) {
setValues(context);
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
appWidgetManager.updateAppWidget(new ComponentName(context,
"类名"), remoteViews);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
setValues(context);
appWidgetManager.updateAppWidget(new ComponentName(context,
"类名"), remoteViews);
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private void setValues(Context context) {
// TODO Auto-generated method stub
/** 初始化周 **/
remoteViews = new RemoteViews(context.getPackageName(),
"布局名");
remoteViews.setTextViewText("要写内容");
/** 初始化天 */
remoteViews.setTextViewText(R.id.wg02_lunar,
SwitchAction.initTitle9(year, month, day));
/** 给title添加点击事件 **/
remoteViews.setOnClickPendingIntent(R.id.wg02_lunar, PendingIntent
.getActivity(context, 0, new Intent(context,
"要跳转的类"), 0));
remoteViews.setTextViewText(R.id.wg02_schedule, str1);
PendingIntent pendingIntent1 = PendingIntent.getActivity(context, 0,
intent1, PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.wg02_schedule, pendingIntent1);
}原理:widget要继承自WidgetProvider,而WidgetProvider是BroadReceiver的子类,
通过remoteviews来将widget内容写入,通过广播来更新widget内容。
widget在创建时先执行onupdate方法,而后执行onreceive方法
当onReceive方法接收到android.appwidget.action.APPWIDGET_UPDATE消息就会调用update方法。
widget很简单,Android基础打好了,做起来很容易!
浙公网安备 33010602011771号