Call an activity method from a fragment

前端 未结 14 859
广开言路
广开言路 2020-11-22 09:08

Trying to call a method in my activity from a fragment. I want the fragment to give the method data and to get the data when the method return. I want to achieve similar to

14条回答
  •  再見小時候
    2020-11-22 09:26

    Update after I understand more how fragments work. Each fragment belongs to a parent activity. So just use:

    getActivity().whatever
    

    From within the fragment. It is a better answer because you avoid superflous casts. If you cannot avoid the casts with this solution use the one below.

    ============

    what you have to do is to cast to the outer activity

    ((MainActivity) getActivity()).Method();
    

    creating a new instance will be confusing the android frame and it will not be able to recognize it. see also :

    https://stackoverflow.com/a/12014834/1984636

    https://stackoverflow.com/a/2042829/1984636

提交回复
热议问题