簡體   English   中英

如何將數據從活動傳遞到片段

[英]How to pass data from activity to fragment

我有一些問題將數據從活動傳遞到其中的片段。 我四處搜索,但沒有找到適合我情況的答案。 我有2個名為CurrentFragment.javaHistoryFragment.java片段類。 我將它們初始化為Activity中的選項卡。

    Tab tab = actionBar.newTab()
            .setText(R.string.tab_current)
            .setTabListener(new TaskitTabListener<CurrentFragment>(
                    this, "current", CurrentFragment.class));
    actionBar.addTab(tab);

    tab = actionBar.newTab()
            .setText(R.string.tab_history)
            .setTabListener(new TaskitTabListener<HistoryFragment>(
                    this, "history", HistoryFragment.class));
    actionBar.addTab(tab);

我被告知要使用setArguments在活動和getArguments的片段。 但是在這種情況下如何在Activity中獲取片段對象? 我不能使用getFragmentManager().findFragmentById()因為片段是以編程方式添加的。

另外,我發現一些帖子說我可能在片段中使用getActivity()來訪問Activity容器中的數據,但對我來說它一直返回null。 有沒有人有這方面的工作實例?

[編輯]我已經更新了我的答案,以便更好地回答您的問題。

您還可以使用getFragmentManager().findFragmentByTag("tag")按標記檢索片段。 但要小心,如果尚未查看選項卡,則片段將不存在。

CurrentFragment curFrag = (CurrentFragment)
    getFragmentManager().findFragmentByTag("current");
if(curFrag == null) {
    // The user hasn't viewed this tab yet
} else {
    // Here's your data is a custom function you wrote to receive data as a fragment
    curFrag.heresYourData(data)
}

如果您希望片段從活動中提取數據,則您的活動將實現片段定義的接口。 在片段的onAttach(Activity activity)生命周期函數中,您可以訪問創建片段的活動,因此您可以將該活動轉換為您定義的接口並進行函數調用。 為此,將接口放在您的片段中(如果要在多個片段之間共享相同的接口,也可以將接口設置為自己的文件):

public interface DataPullingInterface {
    public String getData();
}

然后在您的活動中實現接口,如下所示:

public class MyActivity extends Activity implements DataPullingInterface {
    // Your activity code here
    public String getData() {
        return "This is my data"
    }
}

最后,在onAttach(Activity activity)中的onAttach(Activity activity)方法中,將您收到的活動強制轉換為您創建的接口,以便調用這些函數。

private DataPullingInterface mHostInterface;
public void onAttach(Activity activity) {
    super.onAttach(activity);
    if(D) Log.d(TAG, "onAttach");
    try {
        mHostInterface = (DataPullingInterface) activity;
    } catch(ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement DataPullingInterface");
    }
    String myData = mHostInterface.getData();           
}

暫無
暫無

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

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