how to call function from other fragment class

烈酒焚心 提交于 2019-12-19 12:08:03

问题


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



来源:https://stackoverflow.com/questions/26577597/how-to-call-function-from-other-fragment-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!