一阳准、在fragment中啟動Activity
與在Activity中啟動類似氛堕。下面代碼是當(dāng)點擊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());
第二個參數(shù)需要Serializable。
this.startActivity(intent);
三绕沈、在被啟動的Activity關(guān)聯(lián)的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獲取參數(shù):
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中獲取返回結(jié)果
先改變啟動方式
//this.startActivity(intent);
this.startActivityForResult(intent,10);
重寫下面的方法使得fragment獲取結(jié)果
public void onActivityResult(int requestCode,int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(requestCode+":"+resultCode);
}