2011-10-02 67 views
2

我從小部件開始,並在互聯網上得到了一個非常好的教程,得到了完美的例子運行,但是當我試圖改變一些事情時,我卡住了。如何處理小部件按鈕

事情是:我只想從我的imageButton更改圖像,當我按下它時,我嘗試了一些東西,但似乎沒有任何工作。我沒有看到RemoteView和Intent的工作原理。因此,如果有人能在稍後解釋它,我將不勝感激=)

下面的代碼:

public class HelloWidget extends AppWidgetProvider { 
    private ImageButton wifi; 
    public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget"; 
    public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget"; 

    @Override 
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { 
     RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); 
     Intent configIntent = new Intent(context, ClickOneActivity.class); 
     configIntent.setAction(ACTION_WIDGET_CONFIGURE); 
     Intent active = new Intent(context, HelloWidget.class); 
     active.setAction(ACTION_WIDGET_RECEIVER); 
     PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); 
     PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0); 
     remoteViews.setOnClickPendingIntent(R.id.button_wifi, actionPendingIntent); 
     remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent); 
     appWidgetManager.updateAppWidget(appWidgetIds, remoteViews); 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // v1.5 fix that doesn't call onDelete Action 
     final String action = intent.getAction(); 
     if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) { 
      final int appWidgetId = intent.getExtras().getInt(
       AppWidgetManager.EXTRA_APPWIDGET_ID, 
       AppWidgetManager.INVALID_APPWIDGET_ID); 

      if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) { 
       this.onDeleted(context, new int[] { appWidgetId }); 
      } 

     } else { 
      // check, if our Action was called 
      if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) { 
       Toast.makeText(context, "Teste", Toast.LENGTH_LONG).show(); 
       RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); 
       remoteViews.setInt(R.id.button_wifi, "toogleOnOff", R.drawable.icon); 

      } 
      super.onReceive(context, intent); 
     } 

    } 
} 

有很多的教程代碼我得到了,你可以看到= P

THX因爲現在的

+0

你正在得到什麼錯誤?請提供錯誤日誌。 – GamDroid

回答

1

看起來您需要了解更多關於RemoteViews的信息。當你在RemoteViews對象上調用像setOnClickPendingIntent,setInt等函數時,它基本上只是在內部存儲這些操作和參數。然後,在顯示小部件時,它只會播放這些操作以構建小部件的視圖。因此,在通過調用updateAppWidget將RemoteViews提供給AppWidgetManager之後,除非重新構建整個RemoteView並再次調用updateAppWidget,否則不能再次更改它們。

作爲您的問題的答案,您希望使用狀態列表作爲按鈕的背景。有一個很好的例子here