Skip to content Skip to sidebar Skip to footer

How To Call Function From Other Fragment Class

I'm trying to call this function public void arrowClick() is inside my main fragment public class CounterMain extends Fragment implements View.OnClickListener{ the fragment is

Solution 1:

You can call activity method by this way

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

and from activity you can directly call by this way

FragmentManagerfm= getSupportFragmentManager();//if added by xmlYourFragmentClassfragment= (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:

YourFragmentClassfragment= (YourFragmentClass)fm.findFragmentByTag("yourTag");

Solution 2:

First of all, you can not cast from ACTIVITY to FRAGMENT But to cast from GLOBAL ACTIVITY to your ACTIVITY

Or create INTERFACE and implement it in ACTIVITY

Then cast it in FRAGMENT from ACTIVITY to INTERFACE

And on the question:

See here the right way how to implement

(Basic Communication between two fragments)

the answer by Entreco

Post a Comment for "How To Call Function From Other Fragment Class"