Compose使用快捷方式shortcut

本文介绍了如何在Android7.1及以上版本中创建和管理快捷方式。通过静态定义XML文件如shortcuts.xml来设置快捷菜单,或者使用动态注册在运行时添加快捷方式。文中提供了基于Compose的示例代码,包括创建shortcuts.xml,解析strings.xml,以及在manifest.xml中注册快捷方式。此外,还展示了如何使用Kotlin动态注册快捷方式,并提供了一个添加快捷方式到桌面的函数。

简述

以下代码均基于 compose 编写

Android7.1 开始加入了长按应用弹出快捷菜单

可以通过 shortcut 自定义该弹出菜单,比如我们接下来要实现的功能如下图所示(运行于纯正的 android10 系统上)


弹出菜单可以目前存在两种可选定义形式:

  1. 静态定义:直接写死在 xml 文件,只有 APP 更新重装才可以更新弹出菜单
  2. 动态定义:顾名思义

静态定义

shortcuts.xml

新建文件 res/xml/shortcuts.xml

shortcuts 表示当前快捷菜单,里面有多少个 shortcut 标签,就存在多少个快捷按钮
而事实上,一次性在快捷菜单内最多只能显示四个按钮!

这是一些相关属性定义的解释:

  1. android:enabled 是否激活
  2. android:icon 快捷按钮左侧对应图标
  3. android:shortcutId 该按钮的 ID
  4. android:shortcutShortLabel 快捷按钮文本
<?xml version ="1.0" encoding="utf-8"?>
<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- 定义一个快捷按钮 -->
    <shortcut
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutId="sc1"
        android:shortcutShortLabel="@string/shortcut_title"
        android:shortcutLongLabel="@string/shortcut_long_msg"
        android:shortcutDisabledMessage="@string/shortcut_disable_msg"
        >

        <!-- action表示点击按钮后执行的动作 -->
        <!-- targetClass为目标activity的类文件(直接指向compose默认唯一的activity) -->
        <!-- targetPackage目标类文件所在包 -->
        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.zhiyiyi.hiltdemo.MainActivity"
            android:targetPackage="com.zhiyiyi.hiltdemo"/>
        <categories android:name="android.shortcut.conversation" />
        <capability-binding
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZhillerDev

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值