从 Android 7.1 应用程序快捷方式启动片段(而不是 Activity)

Launch Fragment (instead of Activity) from Android 7.1 App Shortcut

我决定考虑将静态快捷方式添加到应用程序中,使用此页面作为参考:

https://developer.android.com/preview/shortcuts.html

我的快捷方式的 XML 目前看起来是这样的:

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="id"
        android:enabled="true"
        android:icon="@drawable/icon"
        android:shortcutShortLabel="@string/short_label"
        android:shortcutLongLabel="@string/long_label"
        android:shortcutDisabledMessage="@string/disabled_message">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example"
            android:targetClass="com.example.Activity" />
        <categories android:name="android.shortcut.category" />
    </shortcut>
</shortcuts>

问题来自 targetClass 变量,因为我找不到启动 Fragment 而不是 Activity 的方法。我想从快捷方式启动的大多数主页都显示在 ActivityFragments。我怎样才能让 intent 直接启动到 Fragment

您可以执行以下操作:

1) 在shortcuts.xml中指定的意图中,设置自定义意图操作字符串:

 <intent
        android:action="com.your.packagename.custom.name"
        android:targetPackage="com.example"
        android:targetClass="com.example.Activity" />

2) 在 android:targetClass 中指定的 Activity 中检查 getIntent().getAction() 意图操作:

public void onCreate(Bundle savedInstanceState){
    if (CUSTOM_NAME.equals(getIntent().getAction())) {
        // do Fragment transactions here 
    }
}

您可以使用 Shortbread 库轻松实现此目的。

class MainActivity : AppCompatActivity() {
        
    @Shortcut(id = "movies", shortLabel = "Movies", icon = R.drawable.ic_shortcut_movies)
    fun showMovies() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, MoviesFragment())
            .commit()
    }
}