前几天看了下谷歌的发布会,在介绍7.1的适合展示了图标快捷启动的功能,类似于苹果的3d touch ,好酷炫,于是决定自己动手研究一波
在动手开发之前呢先将AS升级到最新版,SDK更新到API25,因为只有API25才能使用这个功能。
首先介绍一下核心的几个类,
1 ShortcutManager 该类是图标信息管理者,主要负责添加,更新或去除图标上的某个条目
2 Shortcutinfo 该类是图标条目信息类,整个类代表一个条目,该类可以设置条目信息,包括图标,标题,主体内容,隐藏内容
3 Shortcutinfo.Binder 该类用来创建一个Shortcut条目,返回Shortcutinfo对象
我们再来看看几个XML属性:
android:shortcutId 条目信息的ID
android:enabled 条目信息是否显示,默认是显示的
android:icon 条目信息的图标
android:shortcutShortLabel 条目信息的标题(有正文的时候不会显示)
android:shortcutLongLabel 条目信息的正文
android:shortcutDisabledMessage 当android:enabled 为false的时候显示的内容
intent 用户点击后跳转的intent对象,强制要求有android:action 属性
OK,了解完上面的属性以后,我们开始动手实现下吧,
1,在AndroidMainfest.xml文件下,在主程序入口的<activity>标签线新加入一个<meta-data>标签,用来设置图标条目的信息,其内容如下:
<meta-data android:name="android.app.shortcuts" android:resource="@xml/shortcuts" />
2 在res目录下新建一个xml文件夹,在文件夹下新建一个shortcuts的xml文件,该文件用来静态设置条目的信息
内容如下:
<?xml version="1.0" encoding="utf-8"?> <shortcuts xmlns:android="http://schemas.android.com/apk/res/android"> <shortcut android:shortcutId="compose" android:enabled="true" android:icon="@mipmap/ic_launcher" android:shortcutShortLabel="@string/compose_shortcut_short_label1" android:shortcutLongLabel="@string/compose_shortcut_long_label1" android:shortcutDisabledMessage="@string/compose_disabled_message1"> <intent android:action="android.intent.action.VIEW" android:targetPackage="com.example.wenxi.myapplication" android:targetClass="com.example.wenxi.myapplication.MainActivity" /> <!-- If your shortcut is associated with multiple intents, include them here. The last intent in the list is what the user sees when they launch this shortcut. --> <categories android:name="android.shortcut.conversation" /> </shortcut> <!-- Specify more shortcuts here. --> </shortcuts>
OK,简单两步,就完成了最简单的demo,当然这还不够,前面我说过,这是静态的,要是需求里面要动态更新条目信息呢,这样我们就不能够用xml去做了,我们需要用代码实现上面的功能
首先,初始化ShortcutManager
ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);//返回shortcutManager 对象
其次,我们需要通过Shortcutinfo.Binder去创建 Shortcutinfo 对象ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1")该方法中传入的参数是当前Activity的上下文和条目的ID拿到 shortcut,对象以后,我们就可以设置条目信息了.setShortLabel("Web site")//设置标题 .setLongLabel("Open"+String.valueOf(index)+"")//设置 .setIcon(Icon.createWithResource(context, R.mipmap.ic_launcher)) //.setActivity(new ComponentName("com.example.wenxi.myapplication","com.example.wenxi.myapplication.MainActivity")) .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com/")))//设置点击跳转的intent对象.build();//创建这里需要注意的是,动态设置必须要设置intent对象,否则会报空指针异常,还有就是不知道是不是因为bug,setActivity并不起作用定义一个list,将shortcut添加到list里面
private List<ShortcutInfo> list=new ArrayList();list.add(shortcut);
最后,通过ShortcutManager添加信息条目或者删除条目:主要有下面三个方法:
setDynamicShortcuts(List)
//将添加一个list
updateShortcuts(List)
// 更新某一个List
removeDynamicShortcuts(List) //删除某个list
removeAllDynamicShortcuts()
.//删除全部信息注:可以有多个list信息集合
本文采用shortcutManager.setDynamicShortcuts(list);运行结果如图:
源码下载地址:http://download.csdn.net/detail/qq_25817651/9673658