@lovesosoi
2018-02-20T15:16:45.000000Z
字数 2168
阅读 894
如果您的应用的目标是Android 7.1(API级别25)或更高,则可以在应用中定义 快捷方式以适应特定操作。快捷方式可让您的用户在应用内快速启动常用或推荐的任务。显示如图
1.res/xml/ 下新建一个xml 文件,此处取名为mandroid.xml
eq:
<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
<shortcut
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">//短名字
<intent
android:action="android.intent.action.VIEW"
android:targetClass="com.gray.quxian.TestActivity"
android:targetPackage="com.gray.quxian" />
<categories android:name="android.shortcut.conversation" />
</shortcut>
</shortcuts>
外部标签为<shortcuts>
,内部标签为<shortcut>
.如果有多个菜单的话,就写平级的<shortcut>
标签。
intent 的 targetPackage
要和manifest
的包名一致,targetClass
的值为目标页面值,<categories>
的标签内的 name 值是固定的。
2.配置清单文件
在程序的主入口下配置<meta-data>
并且name
的值固定,resource
的值为之前的创建的xml文件
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="@xml/shortcuts" />
</activity>
shortcut
的代码创建方式要比静态创建方式复杂些,但是方便我们更新迭代,所以要更加常用些。下面我们就来学习如何代码动态设置shortcut
1.初始化shortcut
/**
* 初始化shortcut
*/
//初始化shortManager
ShortcutManager mSystemService;
mSystemService = getSystemService(ShortcutManager.class);
List<String> mTitle = new ArrayList<>();
private void initShortsCut() {
List<ShortcutInfo> dynamicShortcuts = new ArrayList<>();
//动态设置及添加shortcut 其中getMaxShortCutCountPerActivity的值是5所以mTitle的值不要少于5个,或者一个一个的初始化
for (int i = 0; i < mSystemService.getMaxShortcutCountPerActivity(); 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
}