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。代码如下:

 

 

 

@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		String 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);
		}
		else
			super.onReceive(context, intent);
	}

 

好了,运行下对不对呢?  

打完收工!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值