我必须在按钮点击时删除/添加Android小部件中的布局(按钮位于小部件上)。
这是我的代码
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
updateAppWidget(context, appWidgetManager, appWidgetIds[i]);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getAction().equals(ACTION_HIDE_BALANCE)) {
// CODE TO CHANGE WIDGET UI
}
}
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
CharSequence widgetText = context.getString(R.string.appwidget_text);
// Construct the RemoteViews object
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent intent;
intent = new Intent(ACTION_HIDE_BALANCE);
PendingIntent hideBalancePendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.action_wallet_hide_balance, hideBalancePendingIntent);
intent = new Intent(ACTION_SHOW_BALANCE);
PendingIntent showBalancePendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.action_wallet_show_balance, showBalancePendingIntent);
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
在互联网上搜索我发现PendingIntent技术具有onClickListener效果(已在我的清单中添加了意图过滤器)。
问题在于onRecieve()回调:如何更改小部件UI? 我必须删除像rootView.removeView(layoutView);
中的布局提前致谢。
答案 0 :(得分:0)
好的,我发现这很简单,就像使用标准视图一样。
@Override
public void onReceive(Context context, Intent intent) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetId = 0;
if(intent.getAction().equals(ACTION_HIDE_BALANCE)) {
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.root_view);
views.removeAllViews(R.id.view_to_remove);
appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
super.onReceive(context, intent);
}
很明显,不得不将AppWidgetManager.EXTRA_APPWIDGET_ID额外附加到onClick PendingIntent