简体   繁体   English

如何将数据从活动传递到片段

[英]How to pass data from activity to fragment

I have some problems passing data from an activity to fragments in it. 我有一些问题将数据从活动传递到其中的片段。 I searched around but didn't find an answer which suit my situation well. 我四处搜索,但没有找到适合我情况的答案。 I have 2 fragment class named CurrentFragment.java and HistoryFragment.java . 我有2个名为CurrentFragment.javaHistoryFragment.java片段类。 I initialize them as tabs in an Activity. 我将它们初始化为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);

I was told to use setArguments in the Activity and getArguments in the fragments. 我被告知要使用setArguments在活动和getArguments的片段。 But in this situation how do I get fragment objects in the Activity? 但是在这种情况下如何在Activity中获取片段对象? I can't use getFragmentManager().findFragmentById() since the fragments are added programmatically. 我不能使用getFragmentManager().findFragmentById()因为片段是以编程方式添加的。

Also, I find some posts saying that I may use getActivity() in fragments to access data in the Activity container, but for me it keep returning null. 另外,我发现一些帖子说我可能在片段中使用getActivity()来访问Activity容器中的数据,但对我来说它一直返回null。 Does anyone has a working example of that? 有没有人有这方面的工作实例?

[EDIT] I've updated my answer to better respond to your question. [编辑]我已经更新了我的答案,以便更好地回答您的问题。

You can also retrieve fragments by tag with getFragmentManager().findFragmentByTag("tag") . 您还可以使用getFragmentManager().findFragmentByTag("tag")按标记检索片段。 Be careful though, if the tab has not been viewed yet the fragment will not exist. 但要小心,如果尚未查看选项卡,则片段将不存在。

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

If you want the fragment to pull the data from the activity have your activity implement an Interface defined by the fragment. 如果您希望片段从活动中提取数据,则您的活动将实现片段定义的接口。 In the onAttach(Activity activity) lifecycle function for fragments you get access to the activity that created the fragment so you can cast that activity as the Interface you defined and make function calls. 在片段的onAttach(Activity activity)生命周期函数中,您可以访问创建片段的活动,因此您可以将该活动转换为您定义的接口并进行函数调用。 To do that put the interface in your fragment like this (You can also make the interface its own file if you want to share the same interface among many fragments): 为此,将接口放在您的片段中(如果要在多个片段之间共享相同的接口,也可以将接口设置为自己的文件):

public interface DataPullingInterface {
    public String getData();
}

Then implement the the interface in your activity like this: 然后在您的活动中实现接口,如下所示:

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

Finally in your onAttach(Activity activity) method in CurrentFragment cast the activity you receive as the interface you created so you can call those functions. 最后,在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