Call an activity method from a fragment

前端 未结 14 595
广开言路
广开言路 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:23

    From fragment to activty:

    ((YourActivityClassName)getActivity()).yourPublicMethod();
    

    From activity to fragment:

    FragmentManager fm = getSupportFragmentManager();
    
    //if you added fragment via layout xml
    YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
    fragment.yourPublicMethod();
    

    If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:

    YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
    
    0 讨论(0)
  • 2020-11-22 09:24

    ((YourActivityName)getActivity()).functionName();

    Example : ((SessionActivity)getActivity()).changeFragment();

    Note : class name should be in public

    0 讨论(0)
  • 2020-11-22 09:25

    In kotlin you can call activity method from fragment like below:

    var mainActivity: MainActivity = activity as MainActivity
            mainActivity.showToast() //Calling show toast method of activity
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:27

    For Kotlin developers

    (activity as YourActivityClassName).methodName()
    

    For Java developers

    ((YourActivityClassName) getActivity()).methodName();
    
    0 讨论(0)
  • 2020-11-22 09:27

    I have tried with all the methods shown in this thread and none worked for me, try this one. It worked for me.

    ((MainActivity) getContext().getApplicationContext()).Method();
    
    0 讨论(0)
提交回复
热议问题