【问题标题】:how to call function from other fragment class如何从其他片段类调用函数
【发布时间】:2014-10-26 20:30:48
【问题描述】:

我正在尝试调用这个函数public void arrowClick()

在我的主要片段public class CounterMain extends Fragment implements View.OnClickListener{

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

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

public class CustmoeDialog extends DialogFragment {

我试过((CounterMain)getActivity()).arrowClick();

但我不能使用它上面写着android.support.v4.app.Fragment cannot be cast to my.example.CounterMain

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

当我调用它时,它会让我的应用停止工作

有什么帮助吗?

【问题讨论】:

    标签: android android-activity fragment overflow


    【解决方案1】:

    你可以通过这种方式调用activity方法

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

    从活动中你可以直接通过这种方式调用

    FragmentManager fm = getSupportFragmentManager();//if added by xml
    YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
    fragment.yourPublicMethod();
    

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

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

    【讨论】:

      【解决方案2】:

      首先,你不能从 ACTIVITY 转换为 FRAGMENT 但是要从 GLOBAL ACTIVITY 转换为您的 ACTIVITY

      或者创建INTERFACE并在ACTIVITY中实现

      然后在 FRAGMENT 中从 ACTIVITY 投射到 INTERFACE

      关于问题:

      看这里正确的实现方式

      (Basic Communication between two fragments)

      Entreco 的回答

      【讨论】:

        猜你喜欢
        • 2013-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多