一、在fragment中启动Activity
与在Activity中启动类似。下面代码是当点击ListFragment中的某行时,启动一个Activity。
@Override
public void onListItemClick(ListView l, View v,int position,long id) {
Crime crime=((CrimeAdapter)this.getListAdapter()).getItem(position);
Intent intent=new Intent(this.getActivity(),CrimeActivity.class);
this.startActivity(intent);
}
二、附加extra信息
intent.putExtra(CrimeFragment.EXTRA_CRIME_ID,crime.getmId());
第二个参数需要Serializable。
this.startActivity(intent);
三、在被启动的Activity关联的Fragment中获取extra信息
1)简单方式
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crime_id=(UUID)this.getActivity().getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
this.crime=CrimeLab.get(this.getActivity()).getCrime(crime_id);
}
2)fragment的argument方式
给fragment对象传参:
public static CrimeFragment newCrimeFragment(UUID uuid){
Bundle bundle=newBundle();
bundle.putSerializable(CrimeFragment.EXTRA_CRIME_ID,uuid);
CrimeFragment fragment=new CrimeFragment();
fragment.setArguments(bundle);
returnfragment;
}
fragment获取参数:
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(tag,"CrimeFragment.onCreate()");
//UUID crime_id=(UUID) this.getActivity().getIntent().getSerializableExtra(CrimeFragment.EXTRA_CRIME_ID);
UUID crime_id=(UUID)this.getArguments().getSerializable(CrimeFragment.EXTRA_CRIME_ID);
this.crime=CrimeLab.get(this.getActivity()).getCrime(crime_id);
}
四、刷新ListFragment中的记录
public void onResume() {
super.onResume();
((CrimeAdapter)this.getListAdapter()).notifyDataSetChanged();
}
五、fragment从被启动的Activity中获取返回结果
先改变启动方式
//this.startActivity(intent);
this.startActivityForResult(intent,10);
重写下面的方法使得fragment获取结果
public void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(requestCode+":"+resultCode);
}