按钮单击小部件时更改布局
Posted
技术标签:
【中文标题】按钮单击小部件时更改布局【英文标题】:Changing layout when button clicked on widget 【发布时间】:2013-11-28 17:09:54 【问题描述】:我有一个小部件。我想要做的是在单击按钮时更改布局。
这就是我正在做的:
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);
我的问题在哪里?现在的代码什么都不做。
【问题讨论】:
【参考方案1】:在您的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));
【讨论】:
以上是关于按钮单击小部件时更改布局的主要内容,如果未能解决你的问题,请参考以下文章
通过 QStackedWidget 动态修改同一个小部件的多个实例