Can an Activity access a Fragment to know if a button has been pressed?

后端 未结 4 743
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 03:28

The Objective: I\'m trying to make a notepad application. What my app does is, a button is pressed to create a new note. This pops up a fragment in which th

4条回答
  •  一整个雨季
    2020-12-22 03:53

    Question 1: Is there a way by which pressing the other button in the Fragment could trigger a method in my Activity?

    Sure, the simplest way to do it is:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = MyFragmentBinding.bind(view) // viewBinding enabled
    
        binding.myButton.setOnClickListener {
            (requireActivity() as MyActivity).doSomething() // <--
        }
    }
    

    However, if this Fragment can be used in different Activity instances, then it should expose a Listener with which it exposes its potential events, and doesn't need to know the actual Activity instance it is talking to.

    interface ActionHandler {
        fun onMyButtonClicked()
    }
    
    lateinit var actionHandler: ActionHandler
    
    override fun onAttach(context: Context) {
        super.onAttach(context)
        actionHandler = context as ActionHandler
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val binding = MyFragmentBinding.bind(view) // viewBinding enabled
    
        binding.myButton.setOnClickListener {
            actionHandler.onMyButtonClicked()
        }
    }
    

    This way, your Fragment will always have a listener to talk to even after config changes / process death, which seems to not be the case for most other answers here.

    Question 2: Would this cause the app to become too bloated? Should I keep the button within my activity itself?

    This depends on whether the button actually belongs in the Activity, though it probably doesn't. Most modern apps are written as single-Activity anyway, and unless the view is shared among all screens, it's put inside a Fragment, possibly maybe even using tags from a common layout resource.

提交回复
热议问题