如何解决使用Jetpack导航的工具栏中的BackButton不起作用对于第一个目标
在活动XML中,我有片段标记,例如
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
style="@style/VectorToolbarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent" />
<fragment
android:id="@+id/chat_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
在活动代码中,
navController = findNavController(R.id.chat_nav_host_fragment)
navController.setGraph(R.navigation.one_to_one_chat_nav)
appBarConfiguration = AppBarConfiguration.Builder().build()
toolbar.setupWithNavController(navController,appBarConfiguration!!)
这样做,我可以看到带有工具栏的后退按钮。但是,后退按钮不起作用,或者应用程序无法进入上一个活动。如果我导航到下一个片段,则后退按钮会起作用,并将我带到上一个片段。它仅在第一个片段中无效。
任何帮助或建议都是非常好的。谢谢。
解决方法
我曾经以这种方式放置后退按钮,也许对您有用...:
在活动中:
//
// Back button in Action Bar
//
@Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
然后在onCreate方法中:
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Your title here");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
当然,工具栏必须在xml文件中定义:
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:popupTheme="@style/ThemeOverlay.MaterialComponents.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark" />
希望我能为您提供帮助
,我找到了解决方案。这可能不是最佳答案。但是,它现在可以正常工作。
toolbar.setNavigationOnClickListener {
if(navController.graph.startDestination == navController.currentDestination?.id) {
finish()
} else {
navController.navigateUp()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。