我正在尝试制作一个非常简单的切换开关,并希望存储开关状态以便在不同状态之间切换。 我目前的解决方案是使用一个类布尔变量,但该变量似乎没有改变。
下面是源代码。 如您所见,它迄今为止非常简单,触摸事件正在工作(即,每次都会启动Log语句)。 当小部件首次放置在屏幕上时,它具有文本“Hello!”。 一旦第一次按下,它将更改为“Ontrue”,因此isEnabled明显被设置为true。 但是,在随后的按下中,Log显示isEnabled为false,并且它继续通过else语句而不是if执行。
任何帮助都将不胜感激!
下面是源代码。 如您所见,它迄今为止非常简单,触摸事件正在工作(即,每次都会启动Log语句)。 当小部件首次放置在屏幕上时,它具有文本“Hello!”。 一旦第一次按下,它将更改为“Ontrue”,因此isEnabled明显被设置为true。 但是,在随后的按下中,Log显示isEnabled为false,并且它继续通过else语句而不是if执行。
任何帮助都将不胜感激!
package com.mywidget.widget;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
public class MyWidget extends AppWidgetProvider {
public static final String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
private RemoteViews remoteViews = new RemoteViews("com.mywidget.widget", R.layout.widget1x1);
private boolean isEnabled;
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent intent = new Intent(context, MyWidget.class);
intent.setAction(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
intent, 0);
remoteViews.setOnClickPendingIntent(R.id.BTNwidget, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
Log.i("MyWidget", "Screen pressed! Value is: " + isEnabled);
if (isEnabled) {
// set to off
Log.i("MyWidget", "Setting to off");
// Code to change state
isEnabled = false;
// Update the widget to reflect our changes
remoteViews.setTextViewText(R.id.BTNwidget, "OFF" + isEnabled);
ComponentName cn = new ComponentName(context, HapticWidget.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
} else {
// set to on
Log.i("MyWidget", "Setting to on");
// Code to change state
isEnabled = true;
// Update the widget to reflect our changes
remoteViews.setTextViewText(R.id.BTNwidget, "ON" + isEnabled);
ComponentName cn = new ComponentName(context, HapticWidget.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn, remoteViews);
}
}
super.onReceive(context, intent);
}
}