无法在RemoteView Android上更改ImageView资源

时间:2012-06-19 12:11:56

标签: android

我正在尝试制作一个简单的小部件,其中包含可点击的图片,点击后会发生变化。 我不明白为什么它不起作用

   public class AppWidget extends AppWidgetProvider {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction()==null) {
    context.startService(new Intent(context,
            ToggleService.class));

} else {
super.onReceive(context, intent);
}

}
@Override
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
    context.startService(new Intent(context, 
            ToggleService.class)); 

}
public static class ToggleService extends IntentService { 
    public ToggleService() { 
        super("AppWidget$ToggleService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
    ComponentName me=new ComponentName(this, AppWidget.class);
    AppWidgetManager mgr=AppWidgetManager.getInstance(this);
    mgr.updateAppWidget(me, buildUpdate(this));
    }
    private RemoteViews buildUpdate(Context context) {
    RemoteViews updateViews=new
    RemoteViews(context.getPackageName(),R.layout.widget);
    int a = 1;
    if(a ==
            1) {

            updateViews.setImageViewResource(R.id.phoneState,
            R.drawable.dual_off);
    } else {
    updateViews.setImageViewResource(R.id.phoneState,
    R.drawable.dual_on);
    }
    Intent i=new Intent(this, AppWidget.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,0); 
    updateViews.setOnClickPendingIntent(R.id.phoneState,pi); 
    return updateViews; 
    }
}




 }

我在 for 循环中尝试了各种各样的东西,但它不会改变图像。 我是从一本关于android开发的书中做到的,我是java和android的新手。

1 个答案:

答案 0 :(得分:0)

您将通过 AppWidgetManager 更新您的小部件,after更改remoteview的源代码。在此代码段代码中,我尝试更改小部件的布局,它的AppWidgetProvider名称为 DictionWidgetProvider

private void hideWidgetInstances() {
    hideViews = new RemoteViews(App.getContext().getPackageName(),
    R.layout.hide);
    AppWidgetManager mManager = AppWidgetManager.getInstance(App
    .getContext());
    ComponentName cn = new ComponentName(App.getContext(),
    DictionWidgetProvider.class);
    mManager.updateAppWidget(cn, hideViews);
}

此处应用是一个扩展应用的类。您可以使用应用上下文来访问 ComponentName