问题
Steps are as follows: 1. Run app -> OK, EditText set to "hello" 2. Clear text manually 3. Rotate the device
What I expect is that EditText is set again to "hello" because activity is recreated after rotation. However, EditText is empty. Code:
public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText1);
editText.setText("hello");
}
}
回答1:
Try to add the following to your EditText specification in xml layout:
android:saveEnabled="false"
回答2:
You have to manually do so using saved instance state. It is not about just saving Hello. This is a very common use case. Suppose the user types in something, and then rotates the phone. If due to any reason, the text goes away, the user has to type everything. So you have to save the text somewhere.
https://developer.android.com/guide/topics/resources/runtime-changes.html
So what you have to do is:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Here savedStateValue is a global string
savedStateValue = //Get the Text From Edit Text here;
outState.putString("savedStateKEY", savedStateValue);
}
and in onCreate, do something like this:
if (savedInstanceState != null) {
//Restore the Text to EditText
editText.setText(savedInstanceState.getString("savedStateKEY"));
}
EDIT The second part is why is it happening. It because, you are removing the "Hello" text and on screen orientation change, it is restoring the data from the Bundle that was passed from initial state. In that bundle, there is no "Hello" because you have removed it manually. So if you are using
android:saveEnabled="false"
Then you are making android not to save any state in the EditText.
回答3:
Add configChanges constraint in your manifest file for that activity.
回答4:
add in your manifest.xml
file for that Activity
<activity
android:name=".SignUpActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:label="@string/app_name"
/>
回答5:
EditText
is persistent on device orientation change, you need to use TextView
instead
来源:https://stackoverflow.com/questions/45898179/edittext-not-set-after-device-rotation