【问题标题】:Using variables in Android shortcuts feature xml?在 Android 快捷方式功能 xml 中使用变量?
【发布时间】:2017-02-01 16:13:38
【问题描述】:

我正在使用 Android 的 shortcut 功能,我有以下 xml:

<shortcuts
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="some_id"
        android:enabled="true"
        android:icon="@drawable/ic_icon"
        android:shortcutShortLabel="@string/short_label"
        android:shortcutLongLabel="@string/long_label"
        tools:targetApi="n_mr1">
        <intent
            android:action="android.intent.action.MAIN"
            android:targetPackage="my.package"
            android:targetClass="my.package.MainActivity" />
    </shortcut>
</shortcuts>

有了这个,它就没有问题了。

我可以像在AndroidManifest.xml 中那样在快捷方式xml 文件中使用变量吗:

<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>

所以我想对快捷方式有相同的行为,但不知何故它不起作用:

<intent
    android:action="android.intent.action.MAIN"
    android:targetPackage="${applicationId}"
    android:targetClass="my.package.MainActivity" />

你知道如何在这里使用变量吗?

我想这样做的原因是我们有多个环境具有不同的包名称:my.package.testmy.package.debugmy.package.hotfix 等...

【问题讨论】:

标签: android shortcut


【解决方案1】:

我创建了一个插件,可以在资源中使用 manifestPlaceholders,并且可以与 3.0.0 版的 android gradle 插件一起使用

https://github.com/timfreiheit/ResourcePlaceholdersPlugin

src/main/res/shortcuts.xml:

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut ...>

        <intent
            android:action="android.intent.action.VIEW"
            android:targetClass="com.test.MainActivity"
            android:targetPackage="${applicationId}"/>
    </shortcut>
</shortcuts>

【讨论】:

  • 很棒的插件,省了很多工作。谢谢。希望有一天,Android 能够取代资源中的占位符。到那时,这就是解决方案。
【解决方案2】:

你知道如何在这里使用变量吗?

目前不支持。清单占位符用于清单的清单合并过程。资源没有等价物。

最简单的解决方案是围绕设置专用的构建类型或产品风格。在您的情况下,构建类型似乎是合适的模型。每个构建类型都有一个专用的快捷方式 XML 资源是可行的。理论上,您可以使用应用程序 ID 为每个构建类型提供专用的字符串资源(例如,app_id,在 Gradle 中使用 resValue 设置),然后在单个快捷方式 XML 资源中使用 android:targetPackage="@string/app_id"。但是,我不确定我们是否可以在那里使用字符串资源。

【讨论】:

  • 使用字符串资源是个好主意,但它也不起作用。唯一的解决方案是目前每个构建类型都有多个资源文件,但至少这是有效的。我想避免它,但目前我似乎不能。
  • @ktamas:原则上,可以创建一个 Gradle 插件来执行清单合并样式的变量替换,从而产生资源。它可能需要res-template/xml/shortcut.xml 之类的东西,并根据构建变体和提供的占位符在build/generated/ 中生成正确的XML 资源。我不知道有人建造了这个,如果你为了这种情况自己滚动一个,那就太矫枉过正了。
  • 使用字符串资源不起作用,它将打印地址而不是该地址的值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
相关资源
最近更新 更多