首页 > 解决方案 > 在向上后退按钮上单击导航到活动中的特定片段

问题描述

我正在尝试使用向上(<-)后退按钮从第二个活动导航到第一个活动中底部导航视图中的特定片段。我试过代码

         val actionBar = supportActionBar
         actionBar!!.setDisplayHomeAsUpEnabled(true)

但是,在清单文件中放置父活动时,它不会显示我需要的片段。它会在第一个活动中进入主页片段。

这是我在第一个活动中的片段代码

      btm = findViewById(R.id.navigation) as BottomNavigationView
         btm.setOnNavigationItemSelectedListener { item ->
        var selectedFragment: Fragment? = null
        when (item.itemId) {
            R.id.navigation_home ->
                selectedFragment = ReferFragment.newInstance()
            R.id.navigation_dashboard ->
                selectedFragment = AccountFragment.newInstance()
            R.id.navigation_notifications ->
                selectedFragment = ProfileFragment.newInstance()
        }

        var ft: FragmentTransaction = 
                    supportFragmentManager.beginTransaction()
        ft.replace(R.id.fragment_container, selectedFragment)
        ft.commit()
        true
    }
    var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.replace(R.id.fragment_container, ReferFragment.newInstance())
    ft.commit()

我想在第二个活动中单击 UP backButton 时转到第三个片段。谢谢你

标签: androidkotlin

解决方案


在从第二个活动单击向上返回按钮时,传递一个意图标志。

像下面

Intent mIntent=new Intent(SecondActivity.this,FirstActivity.class);
mIntent.putExtra("IS_FROM_SECOND",true);
startActivity(mIntent);

现在在第一个活动中onCreate()

检查意图

boolean isFromSecond=getIntent().hasExtra("IS_FROM_SECOND");

注意:- 不要在任何其他意图中使用键“IS_FROM_SECOND”。

因此,如果是这种情况,请检查

if(isFromSecond)
  var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.replace(R.id.fragment_container, 3rdFragment.newInstance())
    ft.commit()
}

推荐阅读