7

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

我的片段方法:

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

如何從上述主要活動方法調用,而不使用FragmentById(或)FragmentByTag?

+2

當您使用fragmentTransaction保存片段對象,以後你可以從該對象 –

+0

我沒有」調用任何公共方法Load片段不明白..你可以給任何示例代碼 – hikoo

+0

可能的重複http://stackoverflow.com/questions/10903077/calling-a-fragment-method-from-a-parent-activity?rq=1 – Jamil

回答

1

在活動中使用這樣的事情在這裏裝載的片段:

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

currentFragment = fragment;在這一行中片段是什麼? – hikoo

+0

您正在加載的片段。其中你的功能實現 –

17

首先創建一個接口線

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

最後,當condtion發生您想要調用Fragment方法,只需撥打:

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

((YourFragment Class)fragment)。您的方法();

其工作形成我

+5

片段意味着什麼? – hikoo

4

這意味着你調用一個片段方法

((YourFragmentClass) fragment).Yourmethod(); 
+0

什麼是'片段'? –

相關問題