接了个模块,做便签,所以在学习便签的过程成也对窗口小部件小有收获,分享之:
Widget大小的计算 :(单元格数*74)-2,API上说是为了防止像素计算时的整数舍入导致错所以-2...不是很明白
- --------------------------------------------------------------------------------------------------------------------------
关机在开机后,会刷新桌面上的所有widget,调用其AppWidgetProvider的onReceive->onUpdate->onReceive方法
故必须在 AppWidgetProvider中,处理及面的刷新时,RemoteView内容的显示,或者onclick事件的响应。
生成一个新的小部件的时候的Id分配
Bundle extras = intent.getExtras();
if (extras != null) {
mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
}
// If they gave us an intent without the widget id, just bail.
if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
finish();
}
----------------------------------------------------------------------------------------------------------------------------
获取当前provider在桌面上显示的所有小部件的id值
Bundle extras = intent.getExtras();
if (extras != null) {
int[] appWidgetIds = extras.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS);
if (appWidgetIds != null && appWidgetIds.length > 0) {
this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds);
}
}
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds=appWidgetManager.getAppWidgetIds(new ComponentName(this, myWidgetProviderLarge.class));
----------------------------------------------------------------------------------------------------------------------------
可以在RemoveView中布局的控件,必须在其类上做@RemoteView声明
如源码中的 TextView:
@RemoteView
public class TextView extends View implements ViewTreeObserver.OnPreDrawListener {...}
------------------------------------------------------------------------------------------------------------------------------
如果生成多个内容不同的桌面小部件,并且使其可响应点击事件,打开响应id对应的内容,则需记录每个小部件的appwidgetId,并将其发送给点击事件相应的activity。
如当前activity为小部件的配置活动,点击打开EditWidget.java:
Intent configIntent = new Intent(this, EditWidget.class);
configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
configIntent.setAction(uri.toString());
PendingIntent pendingIntent = PendingIntent.getActivity(EditNote.this, 0,configIntent, 0);
views.setOnClickPendingIntent(R.id.note_appwidget, pendingIntent);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(EditNote.this);
appWidgetManager.updateAppWidget(mAppWidgetId, views);
点击后打开EditWidget.java
Intent t = getIntent();
Log.i("", "this is ===="+t.getAction());
mAppWidgetId = t.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
Log.i("", "this is [" + mAppWidgetId + "] editing!");