[关闭]
@lovesosoi 2018-02-20T15:16:45.000000Z 字数 2168 阅读 894

Android 桌面的二级菜单实现

写在前面的话

如果您的应用的目标是Android 7.1(API级别25)或更高,则可以在应用中定义 快捷方式以适应特定操作。快捷方式可让您的用户在应用内快速启动常用或推荐的任务。显示如图

静态使用 Shortcut

1.res/xml/ 下新建一个xml 文件,此处取名为mandroid.xml
eq:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
  3. <shortcut
  4. android:enabled="true" //该二级菜单是否可用
  5. android:icon="@mipmap/xiansuo" //显示的图标
  6. android:shortcutDisabledMessage="@string/quxian"//不可用时显示的文字
  7. android:shortcutId="settings"//唯一id
  8. android:shortcutLongLabel="@string/settings_long_name" //长名字
  9. android:shortcutShortLabel="@string/settings_short_name">//短名字
  10. <intent
  11. android:action="android.intent.action.VIEW"
  12. android:targetClass="com.gray.quxian.TestActivity"
  13. android:targetPackage="com.gray.quxian" />
  14. <categories android:name="android.shortcut.conversation" />
  15. </shortcut>
  16. </shortcuts>

外部标签为<shortcuts>,内部标签为<shortcut>.如果有多个菜单的话,就写平级的<shortcut>标签。
intent 的 targetPackage要和manifest 的包名一致,targetClass的值为目标页面值,<categories>的标签内的 name 值是固定的。

2.配置清单文件
在程序的主入口下配置<meta-data>并且name的值固定,resource的值为之前的创建的xml文件

  1. <activity android:name=".MainActivity">
  2. <intent-filter>
  3. <action android:name="android.intent.action.MAIN" />
  4. <category android:name="android.intent.category.LAUNCHER" />
  5. </intent-filter>
  6. <meta-data
  7. android:name="android.app.shortcuts"
  8. android:resource="@xml/shortcuts" />
  9. </activity>

动态创建 Shortcut

shortcut的代码创建方式要比静态创建方式复杂些,但是方便我们更新迭代,所以要更加常用些。下面我们就来学习如何代码动态设置shortcut

1.初始化shortcut

  1. /**
  2. * 初始化shortcut
  3. */
  4. //初始化shortManager
  5. ShortcutManager mSystemService;
  6. mSystemService = getSystemService(ShortcutManager.class);
  7. List<String> mTitle = new ArrayList<>();
  8. private void initShortsCut() {
  9. List<ShortcutInfo> dynamicShortcuts = new ArrayList<>();
  10. //动态设置及添加shortcut 其中getMaxShortCutCountPerActivity的值是5所以mTitle的值不要少于5个,或者一个一个的初始化
  11. for (int i = 0; i < mSystemService.getMaxShortcutCountPerActivity(); i++) {
  12. Intent intent = new Intent(this, OtherActivity.class);
  13. intent.setAction(Intent.ACTION_VIEW);
  14. ShortcutInfo info = new ShortcutInfo.Builder(this, "id" + i)//设置id
  15. .setShortLabel(mTitle.get(i))//设置短标题
  16. .setLongLabel("功能:" + mTitle.get(i))//设置长标题
  17. .setIcon(Icon.createWithResource(this, R.mipmap.xiansuo))//设置图标
  18. .setIntent(intent)//设置intent
  19. .build();
  20. dynamicShortcuts.add(info);//将新建好的shortcut添加到集合
  21. }
  22. mSystemService.setDynamicShortcuts(dynamicShortcuts);//设置动态shortcut
  23. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注