如何从其他片段类调用函数 [英] how to call function from other fragment class

查看:156
本文介绍了如何从其他片段类调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图调用这个函数 public void arrowClick()

code> public class CounterMain extends Fragment implements View.OnClickListener {

is inside my main fragment public class CounterMain extends Fragment implements View.OnClickListener{

片段扩展 android.support .v4.app.Fragment

我想从另一个Custmoe Dialog片段中调用此函数

I want to call this function from another Custmoe Dialog fragment

public class CustmoeDialog extends DialogFragment {

((CounterMain)getActivity())。arrowClick();

但我不能用它说 android.support.v4.app.Fragment无法转换为my.example.CounterMain

和 p>

and the

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

它让我的应用程序在我调用它时停止工作

it makes my app to stop working when I call it

有什么帮助?

推荐答案

您可以通过这种方式调用活动方法

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();

如果您通过代码添加片段并在添加片段时使用了标记字符串,请改为使用findFragmentByTag:

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

这篇关于如何从其他片段类调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆