如何使用bundle将数据从一个片段发送到另一个片段

时间:2014-07-02 09:23:37

标签: android android-fragments

我有3个片段A,B,C。在片段A中我有字段说明名称和密码。在片段B中我有字段联系人和country.And在C中我有字段如summary.Now in fragment C我正在呼叫一个Web服务,其中包含来自A和B.的所有参数。我在A中存储了字段。现在在片段B中我必须从A获取包并创建一个新的包并包含来自A和B的字段那个捆绑并在C.中使用。我的问题是,我不能直接在C ????中使用A和B的捆绑包

3 个答案:

答案 0 :(得分:2)

要将包传递给片段,请使用:

fragment.setArguments(bndl);

并在引用片段中使用该包,请使用:

Bundle bndl = fragment.getArguments();

这是最简单,最快捷的方式之一。

答案 1 :(得分:2)

嗨,这是如何使用bundle将数据从一个片段发送到另一个片段

Frament A

Bundle bundle = new Bundle;
bundle.putString(Const.BUNDLE_KEY1, value1);
bundle.putString(Const.BUNDLE_KEY2, value2);
Fragment fragmentB = new FragmentB();
fragmentB.setArguments(bundle);

//然后在这里替换片段

片段B 公共类FragmentB扩展了Fragment {

public static FragmentB newInstance(Bundle bundle) {
    FragmentB fragmentB= new PVResultatFragment();
    Bundle args = new Bundle();
    args.putString(Const.BUNDLE_KEY1, value1);
    args.putString(Const.BUNDLE_KEY2, value2);
    pvf.setArguments(args);
    return fragmentB;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_b, container, false);
    resolver = getActivity().getContentResolver();
    Bundle bundle = getArguments();
    String value1 = bundle.getString(Const.BUNDLE_KEY1);
    String value2 = bundle.getString(Const.BUNDLE_KEY2);

...

答案 2 :(得分:1)

是的,您可以这样做,在解决方案的片段之间传递数据是通过父活动来完成的。

示例代码:

主要活动

    private Bundle  dataBetweenFragment; //Global variable

现在实现此方法,您可以访问数据。

    public void saveData (Bundle data) {
          this.dataBetweenFragment = data;
    }

    public Bundle getSavedData () {
          return this.dataBetweenFragment;
    }

片段A或B或C或任何:

    private MainActivity activity;

    public void onAttach(Activity activity) {
            this.activity = (MainActivity) activity;        
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {   
          super.onCreate(savedInstanceState);   
          /**Get data from Activity **/
          Bundle data = mainActivity.getSavedData();
          String dataString = data.getString("data");
    }


    public void sendDataOtherFragment () {
          Bundle data = new Bundle();
          data.putString("data", "Hi!");
          this.mainActivity.saveData(data);
    }