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

标签 android android-fragments bundle

我有一个 fragment 似乎在屏幕旋转配置更改时自动恢复状态。我可以在日志中验证,只要屏幕旋转,就会在 fragment 中调用 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 已经在 View 中。不过,我们知道正在调用 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 - Fragment自动保存和恢复EditTexts的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24553634/

相关文章:

Android WebView对hr标签进行CSS修改

Android:无法接收 BottomSheetDialog 状态更改回调

android - Thomashaertel 的库作为多选微调器

android - Fragment 中的 ViewPager 在 transaction.remove() 之后消失(维护实例?)

javascript - 使用 bundle.config bundle 2 个具有相同名称和参数的函数的 .js 文件后会发生什么?

android - 我的操作栏的 Holo Light Theme 的意外效果

java - 向 ListView 行中的每个项目添加按钮时出现错误

android - 通过构建器注入(inject)的 Hilt 适配器为空

Ruby on Rails - 列出所有第 3 方库详细信息和许可

ios - iPhone 应用程序中的 .bundle