forked from YoKeyword/Fragmentation
-
Notifications
You must be signed in to change notification settings - Fork 52
7、使用场景- startForResult&启动模式
薛瑄 edited this page Mar 3, 2020
·
1 revision
Fragmentation提供了类似Activity的启动方法:
- 启动新的Fragment,并能接收到新Fragment的数据返回:
startForResult(SupportFragment fragment,int requestCode)
下面是DetailFragment startForResult
ModifyTitleFragment的代码:
public class DetailFragment extends SupportFragment{
private void goDetail(){
// 启动
startForResult(ModifyDetailFragment.newInstance(mTitle), REQ_CODE);
}
// 目标Fragment调用setFragmentResult()后,在其出栈时,会回调该方法
@Override
public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
super.onFragmentResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE && resultCode == RESULT_OK ) {
// 在此通过Bundle data 获取返回的数据
}
}
}
public class ModifyTitleFragment extends SupportFragment{
// 设置传给上个Fragment的数据
private void setResult(){
Bundle bundle = new Bundle();
bundle.putString("title", "xxxx");
setFramgentResult(RESULT_OK, bundle);
}
}
- 以某种启动模式启动Fragment:
start(SupportFragment fragment, int launchMode)
下面是以SingleTask模式重新启动一个已存在的Fragment的标准代码: 比如:HomeFragment->B Fragment->C Fragment,C Fragment以SingleTask模式重新启动HomeFragment
// 任意同栈内的Fragment中:
HomeFragment fragment = findFragment(HomeFragment.class);
Bundle newBundle = new Bundle();
...
fragment.putNewBundle(newBundle);
// 在栈内的HomeFragment以SingleTask模式启动(即在其之上的Fragment会出栈)
start(fragment, SupportFragment.SINGLETASK);
public class HomeFragment extends SupportFragment{
@Override
protected void onNewBundle(Bundle newBundle){
// 在此可以接收到SINGLETASK/SINGTOP启动模式传递的数据 类似Activity中的onNewIntent()
}
}