假設你有2個按鈕:左和右。首先你會重視未決意圖每個(這裏它是從Service#onStart
觸發:
@Override
public void onStart(Intent intent, int startId) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this.getApplicationContext());
int[] allWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
// add listeners for every widget registered
for (int widgetId : allWidgetIds) {
addClickListeners(appWidgetManager, widgetId, root);
}
stopSelf();
}
protected void addClickListeners(AppWidgetManager appWidgetManager, int widgetId, RemoteViews root) {
root.setOnClickPendingIntent(R.id.left, getNavigationIntent(widgetId, R.id.left));
root.setOnClickPendingIntent(R.id.right, getNavigationIntent(widgetId, R.id.right));
}
protected PendingIntent getNavigationIntent(int widgetId, final int id) {
Intent clickIntent = new Intent(this, WidgetProvider.class);
clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
clickIntent.putExtra(TRIGGER, id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
然後,在AppWidgetProvider
做
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Bundle extras = intent.getExtras();
Integer id = (Integer) (extras == null ? null : extras.get(TRIGGER));
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action) && id != null) {
int widgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, 0);
onNavigate(context, widgetId, id);
} else {
super.onReceive(context, intent);
}
}
protected void onNavigate(Context context, Integer widgetId, Integer id) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews root = new RemoteViews(context.getPackageName(), R.layout.app_widget);
if (id == R.id.left) {
root.showPrevious(R.id.scroll);
} else {
root.showNext(R.id.scroll);
}
appWidgetManager.updateAppWidget(widgetId, root);
}
這應該這樣做現在的問題是 - 這隻會在API工作11+,我發現root.setInt(R.id.scroll, "setDisplayedChild", pos)
不能在API 7中工作。
很棒的答案,非常感謝。不幸的是我的應用程序是API 7+,所以我必須等待一段時間才能嘗試上面,但它開闢了一些真正的英寸與我的小工具有很大的關係。感謝分享。 –
我不得不面對同樣的問題,結果只有一個帶有TextView和ImageView的LinearLayout,然後當您檢測到導航事件時,只需更改值即可。沒有花哨的滑動效果,但足夠好 – Bostone
當我在它上面添加動畫時,我的應用程序小部件不起作用。有沒有辦法讓一個家庭應用程序的小部件翻轉工作與動畫? ' ' –