Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

FragmentでBackPressedを捕る取る採る盗る

More than 1 year has passed since last update.

FragmentでBackPressedを捕る

FragmentOnBackPressed.kt
fun View.catchBackPressed(vararg listener: FragmentOnBackPressed) {
    requestFocus()
    setOnKeyListener { _, k, e ->
        if (k == KeyEvent.KEYCODE_BACK && e.action == KeyEvent.ACTION_UP) {
            listener.any { it.onBackPressed() }
        } else {
            false
        }
    }
}

interface FragmentOnBackPressed {
    fun onBackPressed(): Boolean
}
AppFragment.kt
class AppFragment: Fragment(), FragmentOnBackPressed {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        view.catchBackPressed(this)
    }

    override fun onBackPressed(): Boolean {
        return if (flag) {
            some()
            true
        } else {
            false
        }
    }

}

仕様

View.setOnKeyListenerの中でlistener.any { it.onBackPressed() }としているので、trueを返すとそれ以降のonBackPressedを呼び出しましぇん。
つまり...

MyFragment.kt
class MyFragment: Fragment(), FragmentOnBackPressed {

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val viewModel = ViewModelproviders.of(this).get(MyViewModel::class.java)
        view.catchBackPressed(viewModel, this)
    }

    override fun onBackPressed(): Boolean {
        some()
        return true

    }
}

class MyViewModel: ViewModel(), FragmentOnBackPressed {

    override fun onBackPressed(): Boolean {
        someModel()
        return true
    }

}

とすると、MyFragmentonBackPressedは絶対に呼ばれないですね!

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away