我决定考虑在应用程序中添加静态快捷方式,使用此页面作为参考:
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
的方法。我想从快捷键启动的大多数主页都是Activity
中显示的Fragments
。我怎样才能让intent
直接发射到Fragment
呢?
您可以这样做:
1)在shortcuts.xml
中指定的intent中,设置一个自定义intent动作字符串:
<intent
android:action="com.your.packagename.custom.name"
android:targetPackage="com.example"
android:targetClass="com.example.Activity" />
2)检查getIntent().getAction()
在android:targetClass
中指定的活动中的意图动作:
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()
}
}
你也可以在导航组件上使用DeepLink导航重定向,快捷xml意图如下:
<intent
android:action="android.intent.action.VIEW"
android:data="<Your deeplink URI, like appname://feature-to-be-names>"
android:targetClass="activity class with package name"
android:targetPackage="application id"/>
和onCreate() ->在活动中处理深链接导航
intent.dataString?.let {
navHostFragment.findNavController().navigate(Uri.parse(it), false)
}
这将负责多个快捷方式和重定向