如果在外部函数内部初始化,则 setImageViewResource 不起作用

Loo*_*ear 0 android widget imageview

我正在构建一个主屏幕小部件,我的目标是在此小部件内的 ImageView 上设置一个图像,并为此使用setImageViewResource()。和它完美的作品-意味着目标图像R.id.user_button改变其图像资源R.drawable.activity_notification之后onStart()被执行-如果我用这样的:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我必须放入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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Sim*_*mon 5

您需要使用 AppWidgetManager 类的 updateAppWidget 方法:

AppWidgetManager manager = AppWidgetManager.getInstance(context);
manager.updateAppWidget(thisWidget, remoteViews);
Run Code Online (Sandbox Code Playgroud)

祝你好运....