how to call function from other fragment class

2019-02-21 07:14发布

问题:

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?

回答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");


回答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