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
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");
((YourActivityName)getActivity()).functionName();
Example : ((SessionActivity)getActivity()).changeFragment();
Note : class name should be in public
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
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
For Kotlin developers
(activity as YourActivityClassName).methodName()
For Java developers
((YourActivityClassName) getActivity()).methodName();
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();