如何将数据从一个片段传递到另一个片段?

时间:2016-03-17 19:04:50

标签: android

您好我正在使用片段将数据从一个片段传递到另一个片段,使用My Model对象,例如Student with(id,name),但是我无法通过第一个片段传递和查看第二个片段中的数据。

2 个答案:

答案 0 :(得分:0)

  1. 使用静态变量
  2. 如果使用视图寻呼机,则在片段更改时更新片段
  3. 在Fragment事务中,当片段被替换时,在构造函数中发送数据

答案 1 :(得分:0)

您可以使用构造函数或使用 setArgument

将数据从一个片段传递到另一个片段

使用构造函数

ModelStudent student = new ModelStudent(1, "ABCD");
FragmentTwo fragmentTwo = new FragmentTwo(student);

使用setArgument

FragmentTwo fragmentTwo = new FragmentTwo();
Bundle bundle = new Bundle();
bundle.putSerializable("STUDENT", student);
fragmentTwo.setArguments(bundle);

片段1

public class FragmentOne extends Fragment {

    private View rootView;
    private Button btnPassData;

    public FragmentOne() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.frgament_one, container, false);

        btnPassData = (Button) rootView.findViewById(R.id.btnPassData);
        btnPassData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ModelStudent student = new ModelStudent(1, "ABCD");
                // first way
                //FragmentTwo fragmentTwo = new FragmentTwo(student);
                // or second way
                FragmentTwo fragmentTwo = new FragmentTwo();
                Bundle bundle = new Bundle();
                bundle.putSerializable("STUDENT", student);
                fragmentTwo.setArguments(bundle);

                FragmentManager fm = getActivity().getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                ft.replace(R.id.content, fragmentTwo).commit();
            }
        });
        return rootView;
    }
}

片段2

public class FragmentTwo extends Fragment {

    private View rootView;
    private ModelStudent modelStudent;
    private TextView txtStudent;

    public FragmentTwo() {
    }

    public FragmentTwo(ModelStudent modelStudent) {
        this.modelStudent = modelStudent;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.frgament_two, container, false);

        txtStudent = (TextView) rootView.findViewById(R.id.txtStudent);
        Bundle bundle = getArguments();
        ModelStudent student = (ModelStudent) bundle.getSerializable("STUDENT");
        txtStudent.setText("RollNo: " + student.getRollNo() + " Name: " + student.getName());

        return rootView;
    }