Android将数据从片段发送到活动

问题描述:

我正在开发一个Android应用程序,我在一个片段中获取了一些数据,并希望在另一个片段中使用它们.所以我一直在寻找创建一个包,使用简单的getBasicInfos()方法在活动中获取它,该包返回我的包,然后将其发送到另一个片段.但是问题是我不能在活动中使用此方法.

I'm working on an Android app, I get some datas in a fragment and I want to use them in an other fragment. So I was looking to create a bundle, get it in the activity with a simple getBasicInfos() method that return my bundle then send it to my other fragment. But the problem is I can't use this method in my activity.

fragment = new DashboardFragment();
            fragment.getBasicInfos(); //Does not recognize the method
            toolbar.setTitle(getResources().getString(R.string.dashboard));
            break;

我想知道是否有更好的方法或更简单.

I want to know if there is a better way, or more simple.

Fragment 中创建接口,并在 Activity 中实现该接口实例化 fragment = new DashboardFragment(this); 将此作为侦听器传递,并在 Fragment构造函数中保存

Create Interface in Fragment and implement that interface in Activity Then while Instantiating the fragment = new DashboardFragment(this); pass this as the listener and in Fragment constructor save this

public DashboardFragment(FragmentListener listener) {
    this.listener = listener;
}

然后使用此侦听器将数据传递给您的 activity .

And then use this listener to pass the data to your activity.

希望这会有所帮助.