Search code examples
kotlinandroid-activity

Android default back button doesnt work as intended with multiple fragments


I have an app where each page/content is a fragment, on top of that i have an app-menu-bar fragment with buttons to navigate the pages(fragments). My problem is that if i press the same button of the appbar multiple times and after i press the default phone back-button(the left arrow), it does not goes immediatly back to the page before, but it navigates the same fragment for each time i pressed the same button, resulting in remaining on the same page.

E.g. i press to navigate on the "favourites" page 10 times, and after if i want to go back to the homepage, i would have to press the back button 10 times.

class MainActivity : AppCompatActivity() {

private val TAG = "MainActivity"
private var currentFragment: Fragment? = null

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

    if (savedInstanceState != null) {
        // Ripristina il fragment corrente
        currentFragment = supportFragmentManager.getFragment(savedInstanceState, "currentFragment")
    } else {
        // Crea e visualizza il fragment iniziale
        currentFragment = RecyclerFragment()
        supportFragmentManager.beginTransaction()
            .replace(R.id.container_main, currentFragment!!)
            .commit()
    }

    val fragment = AppbarFragment()
    supportFragmentManager.beginTransaction()
        .replace(R.id.container_appbar, fragment)
        .commit()
}

override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    // Salva lo stato del fragment corrente
    if (currentFragment != null) {
        supportFragmentManager.putFragment(outState, "currentFragment", currentFragment!!)
    }
}

}

class AppbarFragment : Fragment() {

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

}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    inflater.inflate(R.menu.app_bar, menu)
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when (item.itemId) {
        R.id.action_favourites -> {
            val favouritesFragment = FavouritesFragment() // Crea un'istanza del fragment delle preferite
            requireActivity().supportFragmentManager.beginTransaction()
                .replace(R.id.container_main, favouritesFragment) // Sostituisci il fragment corrente con il fragment delle preferite
                .addToBackStack(null) // Aggiungi la transazione alla back stack per consentire il ritorno al fragment precedente
                .commit()
            true
        }
        R.id.action_search -> {
            val searchFragment = SearchFragment() // Crea un'istanza del fragment di ricerca
            requireActivity().supportFragmentManager.beginTransaction()
                .replace(R.id.container_main, searchFragment) // Sostituisci il fragment corrente con il fragment di ricerca
                .addToBackStack(null) // Aggiungi la transazione alla back stack per consentire il ritorno al fragment precedente
                .commit()
            true
        }
        else -> super.onOptionsItemSelected(item)
    }
}

} Im new to this and i dont know if there is a quick fix or maybe im just not using the fragments functionality as intended.


Solution

  • You can use

    onBackPressed

        @Override
    public void onBackPressed() {
     
        // implement your override logic here
       return;
    }
    

    You override the default back button built in the phone. You will have to write the logic of what you want it to do.

    Example: With code above the back button is completely disabled. Nothing happens. You can place an intent and when you press the back button it will execute the intent. You can also (in case of note pad) code the logic to show an alert to ask if you want to discard or continue. Basically anything you want.