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

我有一些问题将数据从活动传递到其中的片段.我四处搜索,但没有找到适合我情况的答案.
我有2个名为CurrentFragment. java和HistoryFragment.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);

有人告诉我在Activity中使用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(活动活动)生命周期函数中,您可以访问创建片段的活动,以便您可以将该活动转换为您定义的接口并进行函数调用.为此,将接口放在您的片段中(如果要在多个片段之间共享相同的接口,也可以将接口设置为自己的文件):

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

最后,在CurrentFragment中的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();           
}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...