首先展示一个简单使用示例,直接贴代码
Fragment中的代码
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
//跳转到需求任务子表,需要传对应的参数,每个item点击进入的任务子表不一样
Intent intent = new Intent();
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //注意点1
//TODO 传入这个界面数据请求到的ID
intent.putExtra("position",position);
intent.setClass(getActivity(), SoMaterialRqChildActivity.class);
//getActivity().startActivityForResult(intent, REQUEST_CODE); //注意点2
startActivityForResult(intent, REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 2) {
if (requestCode == 1) {
int position = data.getIntExtra("position", 0);
mLists.remove(position);
adapter.notifyDataSetChanged();
}
}
}
//注意点1
//TODO 传入这个界面数据请求到的ID
intent.putExtra("position",position);
intent.setClass(getActivity(), SoMaterialRqChildActivity.class);
//getActivity().startActivityForResult(intent, REQUEST_CODE); //注意点2
startActivityForResult(intent, REQUEST_CODE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 2) {
if (requestCode == 1) {
int position = data.getIntExtra("position", 0);
mLists.remove(position);
adapter.notifyDataSetChanged();
}
}
}
对应管理Fragment的Activity的代码
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) { //注意点3
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 2) {
Fragment fragment = fmanager.findFragmentById(R.id.ll_common_content);
fragment.onActivityResult(requestCode, resultCode, data);
}
}
//注意点3
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 2) {
Fragment fragment = fmanager.findFragmentById(R.id.ll_common_content);
fragment.onActivityResult(requestCode, resultCode, data);
}
}
跳转后的Activity中的代码
Intent intent = new Intent();
int position = getIntent().getIntExtra("position", 0);
intent.putExtra("position", position);
setResult(RESULT_CODE, intent); //注意点4
finish();
//注意点4
finish();
看到这里,相信大家一目了然了,在此对上面4个注意点进行解释
注意点1:Activity跳转的时候,不能加入此Flag,原因嘛,自行体会
注意点2:Fragment中使用这个方法时,不需要用getActivity()方法
注意点3:管理Activity中必须要重写onActivityResult()方法
注意点4:setResult中传入的参数RESULT_CODE,必须>0
除此之外,需要大家注意的是:
就是关于Activity启动的模式为standard或者singleTop,
SingleTask以及SingleInstance均不会奏效
调用onActivityResult方法会在setResult之前,这并不是我们想要的。
正确的调用顺序:
startActivityForResult()-->setResult()--->onActivityResult()