您好我正在使用片段将数据从一个片段传递到另一个片段,使用My Model对象,例如Student with(id,name),但是我无法通过第一个片段传递和查看第二个片段中的数据。
答案 0 :(得分:0)
答案 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;
}