'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 extend android.support.v4.app.Fragment

I want to call this function from another Custmoe Dialog fragment

public class CustmoeDialog extends DialogFragment {

I tried ((CounterMain)getActivity()).arrowClick();

but I can't use it it says android.support.v4.app.Fragment cannot be cast to my.example.CounterMain

and the

CounterMain x = new CounterMain(); x.arrowClick();

it makes my app to stop working when I call it

any help?



Solution 1:[1]

You can call activity method by this way

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

and from activity you can directly call by this way

FragmentManager fm = getSupportFragmentManager();//if added by 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");

Solution 2:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Swap-IOS-Android
Solution 2