2015-04-04 53 views
0

我學習創建Android部件從https://looksok.wordpress.com/2012/12/15/android-complete-widget-tutorial-including-source-code/擴展的clickCount超過2項

教程教程下面展示瞭如何構建Android窗口小部件一個按鈕和圖像。按下按鈕將改變顯示的圖像。

public class MyWidgetIntentReceiver extends BroadcastReceiver { 

private static int clickCount = 0; 

@Override 
public void onReceive(Context context, Intent intent) { 
    if(intent.getAction().equals("pl.looksok.intent.action.CHANGE_PICTURE")){ 
     updateWidgetPictureAndButtonListener(context); 
    } 
} 

private void updateWidgetPictureAndButtonListener(Context context) { 
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo); 
    remoteViews.setImageViewResource(R.id.widget_image, getImageToSet()); 

    //REMEMBER TO ALWAYS REFRESH YOUR BUTTON CLICK LISTENERS!!! 
    remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context)); 

    MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews); 
} 

private int getImageToSet() { 
    clickCount++; 
    return clickCount % 2 == 0 ? R.drawable.me : R.drawable.wordpress_icon; 
} 

}

我想要做的是延長clickCount多個(12張圖像)。作者評論說: 認沽可繪製在一個ArrayList和按鈕,點擊之後得到繪製相應的clickCount 記住計數器復位,如果它達到的ArrayList的大小,以避免IndexOutOfBounds例外

但我真的對如何做到這一點不知道因爲我只有在Java和Android開發方面的知識。

回答

0

這是我如何做它:

public class MyWidgetIntentReceiver extends BroadcastReceiver { 

private static int clickCount = 0; 

@Override 
public void onReceive(Context context, Intent intent) { 
    if(intent.getAction().equals("com.example.intent.action.CHANGE_PICTURE")){ 
     updateWidgetPictureAndButtonListener(context); 
    } 
} 

private void updateWidgetPictureAndButtonListener(Context context) { 
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_demo); 
    remoteViews.setImageViewResource(R.id.widget_image, getImageToSet()); 

    //REMEMBER TO ALWAYS REFRESH YOUR BUTTON CLICK LISTENERS!!! 
    remoteViews.setOnClickPendingIntent(R.id.widget_button, MyWidgetProvider.buildButtonPendingIntent(context)); 

    MyWidgetProvider.pushWidgetUpdate(context.getApplicationContext(), remoteViews); 
} 

private int getImageToSet() { 

    clickCount++; 
    if (clickCount == 1) { 
     return R.drawable.image1 ; 
    } 
    if (clickCount == 2) { 
     return R.drawable.image2 ; 
    } 
    if (clickCount == 3) { 
     return R.drawable.image3 ; 
    } 
    clickCount = 0; 
    return R.drawable.image4 ; 
} 
}