安卓开发教程30: 注册快捷方式

467 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第30天,点击查看活动详情

前面给大家介绍都是 android 的控件、组件,今天来给大家介绍一个比较有意思的配置项。给应用页面注册快捷方式。

ios 用户都知道在桌面对app的图标长按的时候,会弹出该应用的快捷菜单。其实 android 也有相应的效果,我们可以利用配置项给其进行设置快捷菜单。

例如我们要给 app 设置三个快捷菜单,发沸点、写笔记、草稿箱:

image.png

那接来下我们就来看一下怎么配置这些快捷菜单的吧。

一、设置 AndroidManifest.xml 文件

  1. 我们找到 AndroidManifest.xml 的主 activity(也就是包含 intent-filter -> action & category 的那个)。
  2. 给其添加< mate-data > 标签
  3. 指定 resource 属性(指向 res -> xml 下的文件)
<activity
    android:name=".MainActivaty"
    android:exported="true">
    <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:value=""
        android:resource="@xml/shortcuts"/>
</activity>

注意:meta-data 标签的 name 属性一定要设置为 android.app.shortcuts,否则不会起作用,我之前设置的死活不起作用,最后才发现这个属性没有修改默认值。

二、设置 shortcuts.xml 文件

  1. 在 res -> xml 文件夹下新建 shortcuts.xml 文件。可以直接在xml文件夹上右键 New -> XML -> Shortcuts XML File。

image.png

如果跟我一样 Shortcuts XML File 不可以,也可以选择 Values XML File,之后把新建的文件重命名为 shortcuts.xml 并转移到 xml 文件夹内

  1. 配置 shortcuts.xml 文件。 shortcuts.xml 文件由一对 < shortcuts > 标签包裹,其中每一个快捷菜单为一对 < shortcut > 标签(最多为5个)

  2. 设置 shortcut 标签。shortcut 可以设置快捷菜单的文本,图标,以及要打开的页面。

    • 用 shortcutId 属性, 来设置 shortcut 的唯一标识必须是字段且不相同

    • 用 icon 属性, 来设置快捷菜单的图标

    • 用 shortcutShortLabel 属性, 来设置快捷菜单显示的文本标题(这个地方一定要从@String 中设置字段,否则报错)

    • 用 enabled 属性, 来设置 快捷菜单是否可用,肯定要设置为 true 不然我们干嘛要配置这它

    • 用 intent 标签来,设置点击快捷方式执行的操作

      • 用 action 属性, 来设置点击后执行的操作,可用设置为 android.intent.action.VIEW (这个一定要设置,否则不会显示该快捷菜单)
      • 用 targetClass 属性, 来设置要跳转的类
      • 用 targetPackage 属性, 来设置要跳转的包名
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <shortcut
        android:icon="@drawable/boiling"
        android:shortcutId="jboiling"
        android:shortcutShortLabel="@string/jboiling"
        android:enabled="true">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.example.mytest.Boiling"
            android:targetPackage="com.example.mytest" />
    </shortcut>
    ...
<!--    剩余菜单配置项-->

</shortcuts>

按照我们的配置说明进行配置之后,再次点击运行,然后回到桌面长按 app 图标就会显示出来我们设置的快捷菜单。

快捷菜单也可以拖动到桌面显示。

image.png

今天的内容比较简单主要都是配置信息,大家动手操作一下很容易就可以明白各个属性是干啥用的。