0

I am trying to navigate from an second activity to specific fragment in Bottom Navigation View in first activity by using Up(<-) back Button. i have tried code

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

but,while placing parent activity in Manifest File,it wont show the fragment which is required by me.it is going to Home fragment in the 1st activity.

This is my fragment code in First Activity

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

i want to goto 3rd fragment while clicking on UP backButton in second activity. THANK YOU

1 Answers1

1

On Clicking Up back button from Second Activity pass an Intent Flag.

like below

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

Now in First Activity in onCreate()

check intent

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

Note:- Do not use key "IS_FROM_SECOND" in any other intent.

so if it is the case then check

if(isFromSecond)
  var ft: FragmentTransaction = supportFragmentManager.beginTransaction()
    ft.replace(R.id.fragment_container, 3rdFragment.newInstance())
    ft.commit()
}
Vir Rajpurohit
  • 1,869
  • 1
  • 10
  • 23
  • hello sir, i am new to android development.i have used val actionBar = supportActionBar actionBar!!.setDisplayHomeAsUpEnabled(true) for backButton.How can i assign above code to that button.please help me with this – manoj gundapaneni Jun 27 '18 at 08:06
  • https://stackoverflow.com/questions/11079718/action-bars-onclick-listener-for-the-home-button – Vir Rajpurohit Jun 27 '18 at 08:58
  • the above link is related to activity. my issue is when those activity contains three fragments and backButton redirection will be to specific Fragment.The Above Link Didn't help me sir. – manoj gundapaneni Jun 27 '18 at 10:58