android之appwidget(4)终 appwidget控件更新

android之appwidget(四)终 appwidget控件更新紧接上集,现在我们要实现对appwidget控件的更新。首先是新知识

android之appwidget(四)终 appwidget控件更新

紧接上集,现在我们要实现对appwidget控件的更新。

首先是新知识点介绍:

RemoteViews:已经介绍过了,指的是appwidget中的所有的控件。

componentName:指的是appwidget整个这个对象。

其次提醒下大家,由于appwidget与我们的主进程不是同一个进程,所以我们不能像在主进程中那样的操作,先get一个控件,然后set一个控件。还记得我们第二集上讲的那个么,RemoteViews,我们通过这个对appwidget的控件进行操作。

?

这集目标是我们在appwidget中放入一个textview , 一个imageView,和一个button,我们点击这个button他的textview 和imageview都发生改变。

?

不多说,看代码:

1、首先在appwidget.xml中放入控件,没什么好解释的:

?

<TextView  android:id="@+id/textview"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="你好啊,机器人"    />   <Button     android:id="@+id/button"    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="测试按钮"    />    <ImageView     android:id="@+id/imageview"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:src="@drawable/android_icon_125"    />

?

2、然后在我们的onReceive中进行操作:(这里我们自己定义了一个action,详情看上集)

? ? ?要对控件更新,我们需要几个要点:1、获得控件 2、改变过程 3、将结果显示出来。

获得控件与改变我们需要remoteView,而将结果update出来我们需要AppWidgetManager与ComponentName。代码如下:

?

?

?

@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString action = intent.getAction();if(action.equals(UPDATE_ACTION)){System.out.println("onReceive-----"+action);//新建一个remoteViews,对控件进行操作。RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget);//控件更新:remoteViews.setImageViewResource(R.id.imageview, R.drawable.dialog_icon);remoteViews.setTextViewText(R.id.textview, "请说火星文!");//更新桌面。//获得appwidgetmanager。AppWidgetManager appwidgetManager = AppWidgetManager.getInstance(context);//获得componentName。ComponentName componentname = new ComponentName(context, AppwidgetProvider.class);//更新:appwidgetManager.updateAppWidget(componentname, remoteViews);}elsesuper.onReceive(context, intent);}

?

好了,运行下对不对呢? ?

打完收工!