Android4.0中AppWidget的一些新玩意体验

转载请注明出处:http://blog.csdn.net/izard999/article/details/7444457


最近要把之前做的2.3上面的一些程序移植到4.0上面来,  几乎所有的AppWidget都是我一手操办, 所以这个玩意都是我弄.

我把Android2.3的代码直接拷到4.0的环境下面, 编译然后Push,  直接可以跑, 这是木有问题的.  但是我发现4.0上面有一些新东东是之前2.3上面没有的,

我也读了下官方的文档, 做了些demo, 这里总结给大家, 在以后需要做AppWidget的时候可以得心应手.

1: 应用列表中的预览图

如果你不想你的Widget在应用列表里面显示成那个丑机器人图片的话, 就需要在<appwidget-provider>中设置previewImage属性,例如:

<appwidget-provider 
    android:previewImage="@drawable/widget_preview"
/>

2. Widget可以resize

这个我先没注意到, 玩开发板的时候不小心把系统中带的日历的Widget拖出来,想删没有删掉, 发现边上出来一圈蓝边,于是乎想到是不是可以resize大小呢.?结果一试还真是可以,就翻日历源码的Widget和相应的xml文件,发现在<appwidget-provider>中设置了resizeMode属性, 可以设置让用户横向拉, 纵向拉.  设置minResizeWidth和minResizeHeight可以根据需要指定每次缩放的大小(一般设成一格宽, 当然对于集合来说这个要根据你Widget每个元素的大小,一般遵循的规则是拉伸大小为Widget里面每个元素的大小. 例如我看到BookMarket,他的每个元素是占一行两列,所以此时你设置拉伸大小就要注意了, 最好也设置成每次横向两列, 纵向一行就行了 ).   例如

<!--需要两个方向都可以拉的话,就把他们或起来,android里面很多都是这么做的 -->
<appwidget-provider
  android:resizeMode="horizontal|vertical"
  android:minResizeWidth="146dip"
  android:minResizeHeight="72dip"
/>
以上72和146是怎么计算出来的这个不深说了, 文档上是这么说得.


3.支持很多集合控件

这个事非常让我兴奋的阿, 以前看到我Htc的机子上面Widget有集合控件,支持手势, 但是如果不定制RemoteViews是没办法实现的.

Gallery2中的Widget就是拿StackView去做的.  于是我参照了下Gallery2的源码和官方文档,了解了Widget中使用集合控件的方法.

集合是通过一个RemoteViewService去做的, 然后要创建一个RemoteViewsFactory, 这个接口里面的一些方法下面我会一一解释.

不多说.直接上我写的demo的代码,拿ListView做的,其他集合控件都差不多的使用.

widget_provider.xml

<?xml version="1.0" encoding="utf-8" ?> 
  <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" 
        android:minHeight="220dip" 
        android:minWidth="220dip" 
        android:updatePeriodMillis="0" 
        android:initialLayout="@layout/main" /> 

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
	<ListView
	   android:layout_width="fill_parent"
       android:layout_height="fill_parent" 
	   android:id="@+id/list_data"
	     />
    
    
</LinearLayout>

list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:id="@+id/item_layout" >
	<TextView 
	    android:layout_width="wrap_content"
    	android:layout_height="match_parent"
    	android:id="@+id/tv_key"
    	android:textSize="24dip"/>
	<TextView 
	    android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:id="@+id/tv_value"
    	android:textSize="24dip"
    	android:gravity="right"/>
</LinearLayout>



ListViewService.java

package cn.xuhui.pro;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;

public class ListViewService extends RemoteViewsService {

	@Override
	public RemoteViewsFactory onGetViewFactory(Intent intent) {
		//这里很简单的给ListView一个List就好了
		List<String> list = new ArrayList<String>();
		for(int i = 1; i <= 30; i++) {
			list.add(i + "," + i);
		}		
		
		return new ListRemoteViewsFactory(this, list);
	}
	
	private static class ListRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
		private List<String> mList;
		private Context mContext;
		
		//构造ListRemoteViewsFactory
		public ListRemoteViewsFactory(Context context, List<String> list) {
			mList = list;
			mContext = context;
		}
		
		
		@Override
		public int getCount() {
			//返回count
			return mList.size();
		}

		@Override
		public long getItemId(int position) {
			//类似Adapter里面的getItemId,不用处理,一般直接返回就够了
			return position;
		}

		@Override
		public RemoteViews getLoadingView() {
			//when ListView is scrolled, the loading view is not necessary
			//如果是StackView之类需要显示图片什么的,滑动的时候免得用户看到白板,就设置个Loading的View
			return null;
		}

		@Override
		public RemoteViews getViewAt(int position) {
                        //这个方法相当于返回ListView的一个Item(类似Adapter里面的getView/getItem吧)
                        RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item);
			String[] entry = mList.get(position).split(",");
			rv.setTextViewText(R.id.tv_key, entry[0]);
			rv.setTextViewText(R.id.tv_value, entry[1]);
                        Intent fillInIntent = new Intent(mContext, WidgetClickHandlerService.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			fillInIntent.putExtra("clicked_item", mList.get(position));
			//记住,这里是不可以用setOnClickPendingIntent的,官方API上有说, PendingIntent对于CollectionViews是无效的.
                        rv.setOnClickFillInIntent(R.id.item_layout, fillInIntent);
			return rv;
		}

		@Override
		public int getViewTypeCount() {
			//视图种类, 如果我们的集合里面就只有一种视图,那么返回1.附上官方的api doc
			/*
			Returns the number of types of Views that will be created by getView(int, View, ViewGroup). 
			Each type represents a set of views that can be converted in getView(int, View, ViewGroup). 
			If the adapter always returns the same type of View for all items, this method should return 1
			*/
			return 1;
		}

		@Override
		public boolean hasStableIds() {
			//return True if the same id always refers to the same object.
			//如果返回true, 同一个id总是指向同一个对象
			return true;
		}

		@Override
		public void onCreate() {
			// TODO ready for data source
			//这个方法一般是准备或者处理数据源的,这里不做处理. 可以参看Gallery2的
		}

		@Override
		public void onDataSetChanged() {
			// TODO demo only , no dataSet change, 可以参看Gallery2的
		}

		@Override
		public void onDestroy() {
			mList.clear();
			mList = null;
		}
	}

}

我们点击ListView的Item时就用一个服务简单弹一个Toast就可以了

WidgetClickHandlerService .java

package cn.xuhui.pro;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class WidgetClickHandlerService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		String data = intent.getStringExtra("clicked_item");
		Toast.makeText(this, data, Toast.LENGTH_LONG).show();
	}

}

MyAppWidgetProvider.java

package cn.xuhui.pro;


import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;

public class MyAppWidgetProvider extends AppWidgetProvider {
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
		Intent intent = new Intent(context, ListViewService.class);
		rv.setRemoteAdapter(R.id.list_data, intent);
		//注意,下面这段代码不能少,否则点击没有效果
                Intent clickIntent = new Intent(context, WidgetClickHandlerService.class);
                PendingIntent pendingIntent = PendingIntent.getService(
                context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		rv.setPendingIntentTemplate(R.id.list_data, pendingIntent);
		appWidgetManager.updateAppWidget(new ComponentName(context, MyAppWidgetProvider.class), rv);
	}
}

最后AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.xuhui.pro"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <!--这里必须加上这个权限, 否则报错 -->
        <service 
            android:name=".ListViewService"
            android:permission="android.permission.BIND_REMOTEVIEWS"
            />
        
        <service 
            android:name=".WidgetClickHandlerService"
            />
        
        <receiver android:name=".MyAppWidgetProvider"
            android:label="xh_demo">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                    android:resource="@xml/widget_provider" />
        </receiver>
    </application>

</manifest>

好了, 今天就总结到这里, 以后有时间再来研究一些Widget的东西吧


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
创建 Android 应用程序App Widget,需要以下步骤: 1. 创建 App Widget Provider 类 ```java public class MyWidgetProvider extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // 更 App Widget RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setTextViewText(R.id.tv_widget, "Hello World!"); appWidgetManager.updateAppWidget(appWidgetIds, views); } } ``` 2. 声明 App Widget Provider 在 AndroidManifest.xml 文件声明 App Widget Provider,如下所示: ```xml <receiver android:name=".MyWidgetProvider" android:label="@string/app_name"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/my_widget_info" /> </receiver> ``` 其,MyWidgetProvider 是你的 App Widget Provider 类名,@string/app_name 是你应用的名称,@xml/my_widget_info 是你的 App Widget Provider 的相关信息,需要在 res/xml 目录下创建一个名为 my_widget_info.xml 的文件,并在该文件指定你的 App Widget 的布局和其他属性。 3. 定义 App Widget 的布局 在 res/layout 目录下创建一个名为 widget_layout.xml 的文件,定义 App Widget 的布局,如下所示: ```xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/widget_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp"> <TextView android:id="@+id/tv_widget" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:textColor="#000000" /> </RelativeLayout> ``` 4. 更 App Widget 在 onUpdate() 方法,更 App Widget 的 UI。可以使用 RemoteViews 对象更 App Widget 的 UI,如下所示: ```java @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // 更 App Widget RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout); views.setTextViewText(R.id.tv_widget, "Hello World!"); appWidgetManager.updateAppWidget(appWidgetIds, views); } ``` 5. 安装 App Widget 在应用的首次安装时,需要向用户请求授权,以便创建 App Widget。可以使用以下代码向用户请求授权: ```java // 请求授权 Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, new ComponentName(context, MyWidgetProvider.class)); int REQUEST_PICK_APPWIDGET = 1; ((Activity) context).startActivityForResult(intent, REQUEST_PICK_APPWIDGET); ``` 6. 添加 App Widget 到桌面 可以使用以下代码将 App Widget 添加到桌面: ```java // 添加 App Widget Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds); context.sendBroadcast(intent); ``` 其appWidgetIds 是 App Widget 的 ID 数组,可以在 onUpdate() 方法获取。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值