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

后端 未结 4 749
隐瞒了意图╮
隐瞒了意图╮ 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 04:10

    For triggering a method on click of a button in fragment, there are number of ways to achieve this. Try this.

    If (getActivity() instanceof MainActivity){
         //Getting instance of your activity
         MainActivity instance = ((MainActivity)getActivity());
         //Using the instance calling the method in your activity
         instance.methodName();
    }
    

    Use the above code in your fragment on button click.

    Another way is using Interface, calling its abstract methods in fragment and overriding it MainActivity; on button click those methods will be called.

    Or you can also try using RxEventBus. You can publish it in the fragment and listen in the MainActivity.

    Hope this resolves your issue.

提交回复
热议问题