如何在 Android Widget 类中构建 onReceive 方法来切换 ImageView 的图像?
感谢一些教程,我现在已经构建了我的第一个可用的小 Android Widget。
它有一个 ImageView,当我点击它一次时,它会改变它的图像。
但现在我想多次单击它以更改为另一个图像,就像切换按钮一样。
因此,我在 onReceive 方法中设置了以下 IF 约束:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
try {
if(counter %2 == 0) {
views.setImageViewResource(R.id.iv1, R.drawable.button_state1);
cn1 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn1, views);
counter++;
} else { counter++;
views.setImageViewResource(R.id.iv1, R.drawable.button_state2);
cn2 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager..getInstance(context).updateAppWidget(cn2, views);
}
}
// ...
}
但在我看来,我无法使用 counter++
持续修改我的 int counter
。
有没有办法通过单击我的小部件或其他解决方案来设置我的类的 int ,以在小部件中构建某种切换行为?
在没有运行后台服务的情况下这是否可能?
Thanks to some tutorials I have now built my first working little Android Widget.
It has an ImageView which changes it's image when I click on it once.
But now I want to click on it multiple times to change to another image just like a toggle button.
Therefore I've set the following IF constraint in my onReceive method:
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
try {
if(counter %2 == 0) {
views.setImageViewResource(R.id.iv1, R.drawable.button_state1);
cn1 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager.getInstance(context).updateAppWidget(cn1, views);
counter++;
} else { counter++;
views.setImageViewResource(R.id.iv1, R.drawable.button_state2);
cn2 = new (context, MyDailyPlateWidgetProvider.class);
AppWidgetManager..getInstance(context).updateAppWidget(cn2, views);
}
}
// ...
}
But it seems to me that I can't modify my int counter
with counter++
persistently.
Is there any way to set the int of my class through a click on my widget or an other solution to build some kind of toggle behavior in a widget?
Is this even possible without a running background service?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
否则,您无法增加计数器。假设计数器首先为 0,那么 (counter %2 == 0) 为 true,因此它执行第一部分,并递增计数器。下一次 counter 是 1,所以 (counter %2 == 0) 是 false,所以它执行第二部分...从那时起每次,因为 counter 永远是 1!每次只需增加计数器即可。
In the Else, you fail to increment the counter. Imagine counter is first 0, so then (counter %2 == 0) is true, so it does the first part, and increments the counter. Next time counter is 1, so (counter %2 == 0) is false, so it does the second part... every time from then on, because counter is forever 1! Just increment counter every time.