我是 android 编程的新手,我试图解决这个问题几个小时,但仍然无法让它工作。我正在创建一个有 2 个按钮的小部件。一个按钮可以正常工作(调用活动的按钮),但另一个应该更改图片的按钮(如切换键)不起作用。我得到一个NullPointerException
. 我已经跟踪了这个问题,当它传递给 onReceive 时,似乎 remoteViews 为空
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);
}
}