我是Android编程的新手,我试图弄清楚这几个小时,但仍然无法让它工作。我正在创建一个有2个按钮的小部件。一个按钮工作正常(调用活动的按钮)但另一个假设更改图片的按钮(如togglekey)不起作用。我得到NullPointerException
。我已经跟踪了这个问题,当它传递给onReceive
public class Widget extends AppWidgetProvider {
boolean status = false;
private RemoteViews remoteViews;
Button bMain;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
final int n = appWidgetIds.length;
for(int i = 0; i < n; i++){
final int appWidgetId = appWidgetIds[i];
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
Intent configIntent = new Intent(context, Main.class);
configIntent.setAction("callingActivity");
PendingIntent configPendingIntent = PendingIntent.getActivity(context,
0, configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.bWidgetMain,
configPendingIntent);
configIntent = new Intent(context, Widget.class);
configIntent.setAction("callingibFlash");
configPendingIntent = PendingIntent.getBroadcast(context, 0,
configIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.ibFlash, configPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("callingActivity")) {
Toast.makeText(context, "Main", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals("callingibFlash")) {
remoteViews.setImageViewResource(R.id.ibFlash,
R.drawable.flashlight_on);
} else {
super.onReceive(context, intent);
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
}
}
答案 0 :(得分:0)
我建议将remoteViews
作为局部变量,而不是将引用作为实例变量。您可以通过onReceive()
在Context
实施中获得新的参考,并使用AppWidgetManager
更新您的小部件,就像在onUpdate()
中一样。
@Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals("callingActivity")) {
Toast.makeText(context, "Main", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals("callingibFlash")) {
ComponentName thisWidget = new ComponentName(context, Widget.class);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
myRefactoredUpdate(context, appWidgetManager, appWidgetIds);
// use for loop as in onUpdate to get to your remoteViews
final int n = appWidgetIds.length;
for (int i = 0; i < n; i++) {
final int appWidgetId = appWidgetIds[i];
remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteViews.setImageViewResource(R.id.ibFlash, R.drawable.flashlight_on);
}
} else {
super.onReceive(context, intent);
}
}
一旦你有新的RemoteViews可以调用setImageViewResource()和你想要的任何其他东西。为每个案例调用super.onReceive也可能更好。