【问题标题】:setImageViewResource doesn't work if initialized inside an external function如果在外部函数中初始化 setImageViewResource 不起作用
【发布时间】:2012-09-15 07:32:09
【问题描述】:

我正在构建一个主屏幕小部件,我的目标是在该小部件内的 ImageView 上设置一个图像,为此我使用 setImageViewResource()。而且它工作得很好——意味着目标图像R.id.user_button在执行onStart()之后将其图像资源更改为R.drawable.activity_notification——如果我这样使用它:

public class UpdateWidgetService extends Service {
    public void onStart(Intent intent, int startId) {
        ... //Some code which is not really important
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(),R.layout.widget_layout);
        remoteViews.setImageViewResource(R.id.user_button, R.drawable.activity_notification);
    }
}

问题是我必须将setImageViewResource() 放在 外部函数 中,当尝试构建类似于下面代码的内容时它拒绝工作 - 表示目标图像的图像资源R.id.user_buttononStart() 执行后保持不变.

public class UpdateWidgetService extends Service {
    public void onStart(Intent intent, int startId) {
        ... //Some code which is not really important
        changeImagePicture();
    }
    public void changeImagePicture() {
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(),R.layout.widget_layout);
        remoteViews.setImageViewResource(R.id.user_button, R.drawable.activity_notification);
    }
}

我想我是个菜鸟,我在这里错过了一些非常简单且非常重要的东西。你能指出我的错误,这样我才能让我的代码最终工作;) 谢谢你!

【问题讨论】:

  • 您说您在外部类中更改了它,但您在 UpdateWidgetService 类中显示了一个方法(changeImagePicture)。是这个方法还是外部类?还请准确解释发生了什么。 “拒绝工作”是什么意思?
  • @Simon 你说得对,我只是弄乱了这个 类/函数 定义。我正在尝试使用在“public void onStart()”之外声明的public void changedImagePicture() 更改 ImageResource,这现在无法正常工作。我更新了我的问题,并用斜体字突出了应该发生的事情和实际发生的事情。请检查。如果您需要对此进行更多说明,请告诉我。
  • 好的,这有帮助吗? stackoverflow.com/questions/4433464/…
  • @Simon 实际上没有。我尝试使用此 WidgetUpdate 技巧设置图像并获得相同的结果 - 图片保持不变。我已经调试了几次代码,但仍然没有。有什么想法吗?
  • @Simon 我再次尝试了你的updateAppWidget 技巧,它终于奏效了!您能否发表您的评论作为对这个问题的回答,以便我投票支持? ))

标签: android widget imageview


【解决方案1】:

需要使用AppWidgetManager类的updateAppWidget方法:

AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);

祝你好运……

【讨论】:

  • 像魅力一样工作!谢谢! ;)
  • 这有帮助,发现我注释掉了这一行。希望可以对忘记添加此行的人发出警告。
猜你喜欢
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多