gpt4 book ai didi

android - 带有导航组件的 backstack

转载 作者:行者123 更新时间:2023-12-04 08:38:18 24 4
gpt4 key购买 nike

在两个 fragment 上使用导航组件,我的应用程序当前在 navigateUp() 时销毁了一个 fragment 被调用(使用 setupActionBarWithNavController() ),因此当我输入已删除的 fragment 时,所有进度都丢失了,我试图更改将 fragment 添加到后台堆栈 (并且只有一个 fragment 实例)但我一直在为此而挣扎...
这是一些代码:
主要 Activity :

    override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

loginRepository = LoginRepository()
if (!loginRepository.checkLoggedInState()) {
goToLoginActivity()
}

Log.d("FirebaseMain", "onCreate: ${loginRepository.checkLoggedInState()}")

//MyApplication.app.currentUser
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

navController = Navigation.findNavController(this, R.id.nav_host_fragment)

// setup custom action bar
setSupportActionBar(findViewById(R.id.toolbar))

// adds a return button in the ActionBar.
NavigationUI.setupActionBarWithNavController(this, navController)
}
表单 fragment :
(我想保存它的进度并添加到 backstack 的 fragment )
class FormFragment : Fragment() {

private lateinit var binding: FragmentFormBinding

private val checkListRecyclerAdapter = CheckListRecyclerAdapter(
hashMapOf(
0 to "mirrors",
1 to "blinkers1",
2 to "blinkers11",
3 to "blin4kers",
4 to "blink3e1123rs",
5 to "blink6ers",
6 to "blin53kers",
7 to "blin8kers",
8 to "blin7kers",
9 to "blin43kers",
10 to "blin32kers",
11 to "blin322kers",

)
)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

}

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {

binding = DataBindingUtil.inflate(inflater, R.layout.fragment_form, container, false)

binding.rvCheckList.apply {
// this is used to load the data sequentially from top to bottom,
this.layoutManager = LinearLayoutManager(context)

// the adapter that loads the data into the list
this.adapter = checkListRecyclerAdapter
}

return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)

}

}
在此先感谢您的帮助!

最佳答案

我一直在努力解决类似的问题。
导航组件中的 fragment 不会保持其状态。如果您在导航时保持数据进度,则需要创建一个范围为导航图的 SharedViewModel。
在 fragment 中:

private val navGraphScopedViewModel by navGraphViewModels<NavGraphViewModel>(R.id.your_nav_graph)
创建这个类:
class NavGraphViewModel : ViewModel() {
var sharedData= CustomObject()
}
您可以从所有 fragment 访问和设置数据:
 val data = navGraphScopedViewModel.sharedData
我希望我帮助了你

关于android - 带有导航组件的 backstack,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64686583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com