带导航组件的后盖

问题描述

在两个片段上使用导航组件,目前我的应用程序在调用navigateUp()时(使用setupActionBarWithNavController()销毁了一个片段,因此,当我输入已删除的片段时,所有进度都会丢失,我我正在尝试更改将片段添加到后退堆栈中的情况(,但我一直在努力...

这是一些代码

MainActivity:

    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)
    }

FormFragment:

(我要保存其进度并添加到后堆栈的片段)

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)

    }

}

在此先感谢您的帮助!

解决方法

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

在片段中:

private val navGraphScopedViewModel by navGraphViewModels<NavGraphViewModel>(R.id.your_nav_graph)

创建此类:

class NavGraphViewModel : ViewModel() {
    var sharedData=  CustomObject()
}

您可以从所有片段中访问和设置数据:

 val data = navGraphScopedViewModel.sharedData

希望我能对您有所帮助

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...