我开始使用小部件并在互联网上获得了一个非常好的教程,让示例运行得很完美,但是当我试图改变某些事情时,我被卡住了。
事情是:我只是想在我按下它时改变我的imageButton中的图像,我尝试了一些东西,但似乎没有任何效果。我没有得到RemoteView和Intent如何正常工作。因此,如果有人能够解释它,我会很感激=)
以下是代码:
public class HelloWidget extends AppWidgetProvider {
private ImageButton wifi;
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent configIntent = new Intent(context, ClickOneActivity.class);
configIntent.setAction(ACTION_WIDGET_CONFIGURE);
Intent active = new Intent(context, HelloWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.button_wifi, actionPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
@Override
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
Toast.makeText(context, "Teste", Toast.LENGTH_LONG).show();
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
remoteViews.setInt(R.id.button_wifi, "toogleOnOff", R.drawable.icon);
}
super.onReceive(context, intent);
}
}
}
我有很多教程代码,你可以看到= p
从现在开始
答案 0 :(得分:1)
看起来您需要了解有关RemoteView的更多信息。当您在RemoteViews对象上调用setOnClickPendingIntent,setInt等函数时,它基本上只是在内部存储这些操作和参数。然后,当显示窗口小部件时,它只是回放这些操作以构建窗口小部件的视图。因此,在通过调用updateAppWidget将RemoteViews提供给AppWidgetManager之后,除非重新构建整个RemoteView并再次调用updateAppWidget,否则无法再次更改它们。
作为对您问题的回答,您希望使用状态列表作为按钮的背景。有一个很好的例子here。