我試圖根據RemoteViews複製ToggleButton的功能,所以我可以在我的App Widget中使用。我有一個ImageButton,我已經檢測到點擊,但是我在更改點擊時顯示的圖像時遇到問題。我受到的印象是,我需要強制小部件在點擊後進行更新以顯示更改。任何想法什麼是最好的方式去做呢?AppWidget中的ImageButton更新源
public class WifiWidget extends AppWidgetProvider {
boolean toggleState = false;
public static String ACTION_WIDGET_RECEIVER = "com.nickavv.cleanwidgets.WIFICLICK";
Context myContext;
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
myContext = context;
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.wifi_toggle_layout);
Intent intent = new Intent(ACTION_WIDGET_RECEIVER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
views.setOnClickPendingIntent(R.id.wifiToggleButton, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
switchToggle();
}
}
void switchToggle() {
RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.wifi_toggle_layout);
Log.d("toggleState",""+toggleState);
if(toggleState == false) {
views.setImageViewResource(R.id.wifiToggleButton, R.drawable.wifi_toggle_on);
} else {
views.setImageViewResource(R.id.wifiToggleButton, R.drawable.wifi_toggle_off);
}
toggleState = !toggleState;
Log.d("toggleState",""+toggleState);
}
編輯:添加這switchToggle的底部:
AppWidgetManager myAWM = AppWidgetManager.getInstance(myContext);
ComponentName cn = new ComponentName(myContext, WifiWidget.class);
onUpdate(myContext, myAWM, myAWM.getAppWidgetIds(cn));
因此,我將此添加到switchToggle函數的底部(我將把實際代碼放在問題區域中),但是當我單擊該小部件時,會得到由NullPointerException引起的強制關閉。 – Nick
您可以發佈堆棧跟蹤,更新後的代碼以及NPE在哪一行發生? =) – 2011-09-28 20:59:31
當然,請看上面,我已經添加了它 – Nick