我有一个小部件。我想要做的是在单击按钮时更改布局。
这就是我正在做的事情:
public class MainWidgetProvider extends AppWidgetProvider {
public static String ACTION_MENU_CLICKED = "MenuClicked";
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Intent intent = new Intent(context, MainWidgetProvider.class);
intent.setAction(ACTION_MENU_CLICKED);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);
views.setOnClickPendingIntent(R.id.button2, pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ACTION_MENU_CLICKED)) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);
views.setViewVisibility(R.id.layout1,View.INVISIBLE);
views.setViewVisibility(R.id.layout2,View.VISIBLE);
final int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
我的问题在哪里?现在的代码什么也没做。
答案 0 :(得分:2)
在onUpdate
更新您的代码 -
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main_widget_layout);
views.setOnClickPendingIntent(R.id.button2, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, views);//you are missing this line.
并在您的onReceive
方法中将appWidgetId
替换为 -
int[] appWidgetId = AppWidgetManager.getInstance(context).getAppWidgetIds(
new ComponentName(context, MainWidgetProvider.class));