我目前正在学习Android中的小部件。我想增加计数器值,但是当我点击widget时,它会从0增加到1并停止增加它。我的onRecieve
方法运行正常。
这是我的代码:
public static CheckDate CheckDate;
public static EventList EventList;
public static String EVENT_CLICK = "EventClick";
public String msg;
public RemoteViews rviews;
public AppWidgetManager manager;
public Context cntxt;
public Intent intnt;
public int[] ids;
public int counter = 0;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
CheckDate = new CheckDate();
EventList = new EventList();
manager = appWidgetManager;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
ids = appWidgetIds;
Intent intent = new Intent(context, DayWidget.class);
intent.setAction(EVENT_CLICK);
intent.putExtra("msg", "change");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.Event, actionPendingIntent);
CheckDate.Check();
views.setTextViewText(R.id.Today, CheckDate.Today);
views.setTextViewText(R.id.Event, String.valueOf(counter));
manager.updateAppWidget(ids, views);
}
public void UpdateWidget(){
Bundle extras = intnt.getExtras();
if(extras!=null) {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(cntxt);
ComponentName AppWidget = new ComponentName(cntxt.getPackageName(), DayWidget.class.getName());
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(AppWidget);
rviews = new RemoteViews(AppWidget.getPackageName(), R.layout.widget_layout);
counter ++;
rviews.setTextViewText(R.id.Event, String.valueOf(counter));
appWidgetManager.updateAppWidget(appWidgetIds, rviews);
}
}
public void onReceive(Context context, Intent intent){
intnt = intent;
cntxt = context;
if(EVENT_CLICK.equals(intent.getAction())){
try{
msg = intent.getStringExtra("msg");
}catch(NullPointerException e){
e.printStackTrace();
}
UpdateWidget();
Toast toast = Toast.makeText(cntxt, "OnClick", Toast.LENGTH_LONG);
toast.show();
}
super.onReceive(context, intent);
}
答案 0 :(得分:0)
让您的public int counter = 0;
static
成为public static int counter = 0;
或者将其保存在共享偏好