簡體   English   中英

如何從主要活動中調用片段方法

[英]How to call fragment method from main activity

我在片段類中有方法。 我想從主要活動中調用該方法,但我不想使用FragmentById(或)FragmentByTag。

我的片段方法:

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

如何在不使用FragmentById(或)FragmentByTag的情況下從主要活動中調用上述方法?

首先創建一個界面

public interface MyInterface
{
    void myAction() ;
}

您的片段必須實現此接口。

public MyFragment extends Fragment implements MyInterface

在您的活動中, 定義一個MyInterface類型的字段

  private MyInterface listener ;

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

創建片段並將其添加時:

setListener(myFragment);

最后,當您想調用Fragment方法的情況發生時,只需調用:

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

這意味着您調用片段方法

((YourFragmentClass) fragment).Yourmethod();

為了更好地解釋user5466222的答案:

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

在“活動”中,使用類似以下內容的方式加載片段:

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

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

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

(((YourFragment類)片段)。您的method();

它的工作形式是我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM