提问者:小点点

如何通过按返回按钮移动到主页片段


我使用运动布局创建了一个自定义导航抽屉,其中我有图像视图、文本视图和导航主机片段(片段容器视图)。问题是,当我单击导航抽屉中的任何视图时,它会打开一个片段,但单击后退按钮时,它会关闭应用程序。

这是我的主要活动.kt文件

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val contactus = findViewById<TextView>(R.id.contact_us)
        val drawer = findViewById<ImageView>(R.id.image8)
        val tandc = findViewById<TextView>(R.id.termsandconditions)
        val motionLayout = findViewById<MotionLayout>(R.id.motion_layout)


        contactus.setOnClickListener {

            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, contact_us_fragment())
                commit()

                motionLayout.transitionToStart()


            }
        }
        drawer.setOnClickListener {

            motionLayout.transitionToEnd()
            motionLayout.transitionToStart()
        }
        tandc.setOnClickListener {
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.fragmentContainerView2, TandCFragment())
                commit()

                motionLayout.transitionToStart()

            }
        }
    }
}

如何在按下后退按钮时移动到主页片段?


共2个答案

匿名用户

我相信你必须实现onBackPressed()方法。当用户向后按/向后滑动时,将调用此值。

override fun onBackPressed() {
    // Code here to handle going to fragment
}

匿名用户

您可以将片段添加到后退堆栈并为其提供 id,然后使用此 id 弹出后退堆栈。

    supportFragmentManager.beginTransaction()
    .add(yourFragment);
    .addToBackStack("YourFragmentTag");
    .commit()
 

然后将堆栈弹出到这个片段

 override fun onBackPressed() { 
    getFragmentManager().popBackStack("YourFragmentTag", 0);
 }