写在前面的话
静态使用 Shortcut
1.res/xml/ 下新建一个xml 文件,此处取名为mandroid.xml
eq:<?xml version="1.0" encoding="utf-8"?>
android:enabled="true" //该二级菜单是否可用 android:icon="@mipmap/xiansuo" //显示的图标 android:shortcutDisabledMessage="@string/quxian"//不可用时显示的文字 android:shortcutId="settings"//唯一id
android:shortcutLongLabel="@string/settings_long_name" //长名字 android:shortcutShortLabel="@string/settings_short_name">//短名字
android:action="android.intent.action.VIEW"
android:targetClass="com.gray.quxian.TestActivity"
android:targetPackage="com.gray.quxian" />
外部标签为,内部标签为.如果有多个菜单的话,就写平级的标签。
intent 的 targetPackage要和manifest 的包名一致,targetClass的值为目标页面值,的标签内的 name 值是固定的。
2.配置清单文件
在程序的主入口下配置并且name的值固定,resource的值为之前的创建的xml文件
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
动态创建 Shortcut
shortcut的代码创建方式要比静态创建方式复杂些,但是方便我们更新迭代,所以要更加常用些。下面我们就来学习如何代码动态设置shortcut
1.初始化shortcut/**
* 初始化shortcut
*/
//初始化shortManagerShortcutManager mSystemService;
mSystemService = getSystemService(ShortcutManager.class);
List mTitle = new ArrayList<>();private void initShortsCut() {
List dynamicShortcuts = new ArrayList<>();
//动态设置及添加shortcut 其中getMaxShortCutCountPerActivity的值是5所以mTitle的值不要少于5个,或者一个一个的初始化
for (int i = 0; i
Intent intent = new Intent(this, OtherActivity.class);
intent.setAction(Intent.ACTION_VIEW);
ShortcutInfo info = new ShortcutInfo.Builder(this, "id" + i)//设置id
.setShortLabel(mTitle.get(i))//设置短标题
.setLongLabel("功能:" + mTitle.get(i))//设置长标题
.setIcon(Icon.createWithResource(this, R.mipmap.xiansuo))//设置图标
.setIntent(intent)//设置intent
.build();
dynamicShortcuts.add(info);//将新建好的shortcut添加到集合
}
mSystemService.setDynamicShortcuts(dynamicShortcuts);//设置动态shortcut}
2.更新shortcut
要通过id去更新shortcutprivate void updataShortCut(int id) {
Intent intent = new Intent(this, OtherActivity.class);//目标页面
intent.setAction(Intent.ACTION_VIEW);
ShortcutInfo info = new ShortcutInfo.Builder(this, id)
.setShortLabel("已修改")//设置短标题
.setLongLabel("功能:已修改修改")//设置长标题
.setIcon(Icon.createWithResource(this, R.mipmap.fengji))//设置图标
.setIntent(intent)
.build();
mSystemService.updateShortcuts(Arrays.asList(info));//更新shortcut}
3.删除shortcut
如果app的功能点被迭代了删除了,那么该功能的shortcut的点击会出现崩溃的,我们需要让这个shortcut失效。同更新shortcut,都是通过id 进行操作。/**
* 删除已有功能后该二级菜单失效
*/private void deleteShortCut(int index) {
List infos = mSystemService.getPinnedShortcuts(); //遍历出该id的shortcut
for (ShortcutInfo info : infos) { if (info.getId().equals("id" + index)) {
mSystemService.disableShortcuts(Arrays.asList(info.getId()), "暂无改功能");
}
} //动态删除该功能
mSystemService.removeDynamicShortcuts(Arrays.asList("id" + index));
}
代码中删除shortcut之后,android home界面中的shortcut 就回被置灰,点击弹toast 为 disableShortcuts 的内容。
总结
shortcut 是 Android 7.0以后 google 新增的功能,体验类很棒,除了增加了应用功能的快速入口,没有其他影响,所以我觉得只要 app 适配了 7.0,8.0 ,这个功能就可以加上,提高用户的体验。本篇教学只是简单的教学,更深入的学习可以看文章开头的 google 文档,会有一些提高的。