我正在尝试在 android 小部件中创建一个按钮,该按钮增加一个值并将其设置在文本视图上。但该值并未更新计数器编号。
这是我的 DemoUI.java 类
package com.example.widget2;
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.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DemoUI extends AppWidgetProvider {
public static String MY_WIDGET_UPDATE="ACTION_BUTTON1";
RemoteViews remoteViews;
@Override
public void onReceive(Context context, Intent intent){
super.onReceive(context, intent);
final String action=intent.getAction();
if(intent.getAction().equals(MY_WIDGET_UPDATE)){
int num;
num=intent.getIntExtra("num",1);
Toast.makeText(context, num, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int []appWidgetIds){
int num=1;
ComponentName comp=new ComponentName(context,DemoUI.class);
int []allWidgetIds=appWidgetManager.getAppWidgetIds(comp);
for(int widgetIds:allWidgetIds){
remoteViews=new RemoteViews(context.getPackageName(),R.layout.main);
Log.w("WidgetExample2",String.valueOf(num));
remoteViews.setTextViewText(R.id.text1, String.valueOf(++num));
//register listener
Intent intent=new Intent(context,DemoUI.class);
intent.setAction(MY_WIDGET_UPDATE);
//intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
intent.putExtra("num", num++);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent);
//committing changes to the widget
appWidgetManager.updateAppWidget(widgetIds, remoteViews);
}
}
}
// 文本视图仅显示 num 静态值,并且不会在单击按钮时更新它。