封装Fragment不依赖于Activity
本文地址:http://blog.csdn.net/caroline_wendy
Fragment直接托管activity的intent会破坏Fragment的封装性。
可以使用newInstance()的静态方法,完成fragment实例及bundle对象的创建,
然后将argument放入bundle中,最后再附加给fragment.
newInstance代码:
public static CrimeFragment newInstance(UUID crimeId) { Bundle args = new Bundle(); args.putSerializable(EXTRA_CRIME_ID, crimeId); CrimeFragment fragment = new CrimeFragment(); fragment.setArguments(args); return fragment; }
Activity创建Fragment:
protected Fragment createFragment() { // return new CrimeFragment(); UUID crimeId = (UUID)getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID); return CrimeFragment.newInstance(crimeId); }
获取Argument数据:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(EXTRA_CRIME_ID); UUID crimeId = (UUID)getArguments().getSerializable(EXTRA_CRIME_ID); mCrime = CrimeLab.get(getActivity()).getCrime(crimeId); //依赖activity获取crime }
时间: 2024-10-02 21:44:04