是否有使用 Jetpack/androidx 首选项库以及导航组件/单一事件的示例?我看到的所有示例(例如 Google's example )都使用 supportFragmentManager 并替换 FrameLayout 的内容。
使用导航组件导航到 PreferenceFragmentCompat() 几乎可以工作,因为它显示了“首选项”页面,但缺少所有工具栏/导航图标。它只是植入到前一个片段之上,因此要退出它,您需要点击硬件后退按钮。
看起来此问题已向 Google 问题跟踪器提交 here
最佳答案
我刚刚遇到了同样的问题,这就是我的实现方式。在进入代码之前,我想先做一个快速总结。我有一个事件和两个片段。其中一个片段是主片段,即应用程序的主屏幕,另一个片段是显示设置的片段。我最终没有使用 SupportFragmentManager
( which Google shows in their settings guide ),因为我遇到了同样的问题, View 只会出现在前一个 View 的顶部。因此,我只是导航到设置片段,就像使用 findNavController().navigate(...)
导航到单个事件架构中的任何其他片段一样。
首先,您需要将适当的依赖项添加到您的应用build.gradle
:
dependencies {
...
// androidx Preferences
implementation "androidx.preference:preference-ktx:1.1.0"
// androidx Navigation
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.0'
然后,我按照 Google's navigation guide 中所述设置了用于导航的 MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
NavigationUI.setupActionBarWithNavController(
this, this.findNavController(R.id.nav_host_fragment)
)
}
// Allows the up arrow to navigate back to the navigation host fragment.
override fun onSupportNavigateUp(): Boolean {
return Navigation.findNavController(this, R.id.nav_host_fragment).navigateUp()
}
}
之后,设置一个由 MainActivity.kt
托管的片段。当您打开应用程序时会出现此片段。我将其命名为 MainFragment.kt
。请参阅Google's menu guide获取有关创建单击工具栏中的三点图标时展开的下拉菜单的帮助。
class MainFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Show the three dot icon in the top right had corner of the toolbar
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
// Navigate to the settings fragment when the options menu item is selected
R.id.settings -> {
findNavController().navigate(MainFragmentDirections.actionMainToSettings())
true
}
else -> super.onOptionsItemSelected(item)
}
}
// Inflates menu.xml when the three dot icon is clicked
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu, menu)
}
}
最后,设置片段非常容易实现。有关如何设置的信息,请参阅 Google 的设置指南(请参阅上面的链接)。
class MySettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
}
另外,不要忘记将片段连接到 nav_graph.xml 中。请引用上面链接的 Google 导航指南以获取相关示例。
希望这有帮助!
关于android-preferences - AndroidX 首选项和导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59586207/