ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

android-片段自动保存和恢复EditTexts的状态

2019-10-29 11:28:53  阅读:207  来源: 互联网

标签:android-fragments bundle android


我有一个片段,似乎在屏幕旋转配置更改后会自动恢复状态.每当旋转屏幕时,我都可以在日志中验证片段中是否调用了onCreatView.尽管调用了applyDefaults(),但当屏幕旋转并调用onCreateView()时,用户所做的草稿条目将保留.

我的理解是,我必须将状态保存在onSaveInstanceState()中,然后在onCreateView()中进行还原,但这似乎并非如此.有人可以解释吗?

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.d(TAG, "onCreateView()");
    View view = inflater.inflate(R.layout.fragment_email_entry, container, false);

    m_hostNameEditText = (EditText) view.findViewById(R.id.hostNameEditText);
    // set reference for other fields

    applyDefaultsForNewEmailAccount();
    return view;
}

private void applyDefaults() {
    m_hostNameEditText.setText("");
    // set other defaults
}

这可能与我的Activity继承自SingleFragmentActivity的事实有关,因此也许它看到该片段已在视图中.不过,我们知道正在调用Fragment.onCreateView().

public abstract class SingleFragmentActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_fragment_activity);
        FragmentManager fragmentManager = getFragmentManager();
        Fragment fragment = fragmentManager.findFragmentById(R.id.single_frame_container);
        if (fragment == null) {
            fragment = createFragment();
            fragmentManager.beginTransaction()
                    .add(R.id.single_frame_container, fragment)
                    .commit();
        }
    }

    public abstract Fragment createFragment();
}

解决方法:

Just like an activity, a fragment will automatically save the data of
any fragment View component in the Bundle by the View component’s id.
And just like in the activity, if you do implement the
onSaveInstanceState( ) method make sure you add calls to the
super.onSaveInstanceState( ) methods so as to retain this automatic
save of View data feature.

source

标签:android-fragments,bundle,android
来源: https://codeday.me/bug/20191029/1959553.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有