Java 如何从主要活动调用片段方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35747346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:05:30  来源:igfitidea点击:

How to call fragment method from main activity

javaandroidandroid-fragmentsandroid-activityfragmentmanager

提问by hikoo

I have method in fragment class. I want to call that method from main activity but I don't want to use FragmentById (or) FragmentByTag.

我在片段类中有方法。我想从主要活动中调用该方法,但我不想使用 FragmentById(或)FragmentByTag。

My fragment method:

我的片段方法:

public void setItemFromDrawer(String sourceTag, String destTag) {
    //dosomething
}

How to call above method from main activity without using FragmentById (or) FragmentByTag?

如何在不使用 FragmentById(或)FragmentByTag 的情况下从主活动调用上述方法?

回答by Khizar Hayat

In Activity use something like this where you load your fragment:

在 Activity 中使用类似这样的东西来加载你的片段:

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(container, fragment);

transaction.addToBackStack(null); // if you want to store transaction        
transaction.commit();
currentFragment = fragment; // currentFragment is global Fragment variable

Use following line where you want to call fragment's method

在要调用片段方法的地方使用以下行

currentFragment.setItemFromDrawer("sourceTag","destTag");

回答by Farhad Faghihi

First create an interface

首先创建一个接口

public interface MyInterface
{
    void myAction() ;
}

Your fragment must implement this interface.

您的片段必须实现此接口。

public MyFragment extends Fragment implements MyInterface

In your activity, define a field of type MyInterface:

在您的活动中,定义一个 MyInterface 类型的字段

  private MyInterface listener ;

  public void setListener(MyInterface listener)
  {
     this.listener = listener ;
  }

When creating your fragment and adding it :

创建片段并添加它时:

setListener(myFragment);

Finally, when the condtion happens that you want to call the Fragment method, just call :

最后,当您想调用 Fragment 方法时,只需调用:

listener.myAction() ; // this will call the implementation in your MyFragment class.

回答by user5466222

((YourFragment Class) fragment).Your method();

((YourFragment Class) 片段)。你的方法();

its worked form me

它的工作形式我

回答by user5466222

it means your calling a fragment method

这意味着你调用了一个片段方法

((YourFragmentClass) fragment).Yourmethod();

回答by Sif

To better explain the answer by user5466222:

为了更好地解释user5466222的答案:

YourFragmentClass fragment = new YourFragmentClass();
((YourFragmentClass) fragment).yourmethod();