我正在学习按照https://looksok.wordpress.com/2012/12/15/android-complete-widget-tutorial-including-source-code/
的教程创建Android小部件教程展示了如何使用一个按钮和图像构建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张图片)。作者评论说:
将drawable放在ArrayList中,单击按钮后获取与clickCount对应的drawable
如果达到ArrayList的大小,请记住重置计数器以避免IndexOutOfBounds异常
但我真的不知道如何做到这一点,因为我刚开始掌握Java和Android开发知识。
答案 0 :(得分: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 ;
}
}