Android默认的返回按钮在使用多个片段时无法按预期工作。

huangapple go评论49阅读模式
英文:

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 go immediately 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 to 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.
例如,我按下导航到“收藏夹”页面的按钮10次,然后如果我想返回到主页,我将不得不按下返回按钮10次。

I'm new to this and I don't know if there is a quick fix or maybe I'm just not using the fragments functionality as intended.
我对此还很陌生,不知道是否有快速解决方法,或者我可能只是没有按照片段功能的意图使用它。

英文:

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.

答案1

得分: 0

你可以使用以下代码来自定义返回按钮的行为:

@Override
public void onBackPressed() {
    // 在这里实现你的自定义逻辑
    return;
}

你可以重写手机中内置的默认返回按钮行为。你需要编写你想要的具体逻辑。

例如:使用上面的代码,返回按钮将完全被禁用,不会触发任何操作。你可以放置一个意图(intent),当按下返回按钮时,它将执行这个意图。你还可以(在记事本的情况下)编写逻辑以显示一个提示,询问是否要放弃或继续。基本上,你可以实现任何你想要的功能。

英文:

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.

huangapple
  • 本文由 发表于 2023年5月17日 18:19:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271020.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定