Fragment中EditText文字的记忆性

Fragment中EditText文字的记忆性

遇到问题

第一次加载Fragment时,给EditText赋值后"value1",popBackStack()后,重新加载这个Fragment,并且给EditText赋值为“value2”,可是页面上显示EditText仍然为“value1”。

RegisterActivity.java内

	if (fragmentStep1 == null) {
		fragmentStep1 = new FragmentRegisterStep1();
		fragmentStep1.setStep1Listener(this);
	}
	fragmentStep1.setMobile(mobile);
	tx.replace(R.id.id_content, fragmentStep1, "FragmentRegisterStep1");

FragmentRegisterStep1.java内

  • 错误写法:
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		。。。
		mobileEt.setText(mobile);
	}

错误原因

Fragment.java源码

 /**
     * Called when all saved state has been restored into the view hierarchy
     * of the fragment.  This can be used to do initialization based on saved
     * state that you are letting the view hierarchy track itself, such as
     * whether check box widgets are currently checked.  This is called
     * after {@link #onActivityCreated(Bundle)} and before
     * {@link #onStart()}.
     *
     * @param savedInstanceState If the fragment is being re-created from
     * a previous saved state, this is the state.
     */
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        mCalled = true;
    }

当fragment已存在时,重新加载会执行onViewStateRestored把原有的控件数据重新赋值回来。onViewStateRestored在onActivityCreated(Bundle)后面执行,所以onViewCreated里面的mobileEt被覆盖掉了。

Fragment中EditText文字的记忆性_第1张图片

解决方案

在onViewStateRestored后面重新给控件赋值。

  • 正确写法1:
  @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        mobileEt.setText(mobile);
    }
  • 正确写法2:
 @Override
    public void onResume() {
        super.onResume();
        mobileEt.setText(mobile);
    }

你可能感兴趣的:(Fragment中EditText文字的记忆性)