1

我正在尝试制作一个带有可点击图像的简单小部件,当它被点击时会改变。我不明白为什么它不起作用

   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 的新手。

4

1 回答 1

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);
}

这里的App是一个扩展Application的类。您可以使用 Application Context 来访问ComponentName

于 2012-06-19T12:30:59.250 回答