栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何正确将片段的实例状态保存在后堆栈中?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何正确将片段的实例状态保存在后堆栈中?

要正确保存实例状态,Fragment请执行以下操作:

1.在片段中,通过覆盖保存实例状态

onSaveInstanceState()
并在中还原
onActivityCreated()

class MyFragment extends Fragment {    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        ...        if (savedInstanceState != null) { //Restore the fragment's state here        }    }    ...    @Override    public void onSaveInstanceState(Bundle outState) {        super.onSaveInstanceState(outState);        //Save the fragment's state here    }}

2.而且很重要的一点,在活动中,你必须保存片段的实例在

onSaveInstanceState()
和恢复
onCreate()

class MyActivity extends Activity {    private MyFragment     public void onCreate(Bundle savedInstanceState) {        ...        if (savedInstanceState != null) { //Restore the fragment's instance mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName"); ...        }        ...    }    @Override    protected void onSaveInstanceState(Bundle outState) {        super.onSaveInstanceState(outState);        //Save the fragment's instance        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);    }}

希望这可以帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/366845.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号