我创建了两个xml文件,activity_main
其他一个是activity_main_land
。两者都有2个EditText字段。两者都有ID,并且两个XML ID都相同。调用onConfigchange()
方法时,我更改了XML文件。现在当我旋转设备时,EditText丢失了数据。你能帮我解决这个问题。
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Toast.makeText(MainActivity.this, "simple", Toast.LENGTH_SHORT).show();
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
Toast.makeText(MainActivity.this, "Landscape", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main_land);
}else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(MainActivity.this, "portreate", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
}
我也试过参考:
答案 0 :(得分:5)
@Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
...
...
String userName, password;
if(savedInstanceState!=null)
{
userName = savedInstanceState.getString("user_name");
password= savedInstanceState.getString("password");
}
if(userName != null)
userNameEdtTxt.setText(userName);
if(password != null)
passEdtTxt.setText(password);
}
....
@Override
protected void onSaveInstanceState (Bundle outState)
{
outState.putString("user_name", userNameEdtTxt.getText().toString());
outState.putString("password", passEdtTxt.getText().toString());
}
答案 1 :(得分:1)
试试这个对我来说很好。
在你的两个xml文件中,保持edittexts id相同,
public class MainActivity extends Activity {
EditText userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userName = (EditText)findViewById(R.id.edtUserName);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
String storedUsername = userName.getText().toString();
// landscape mode
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.activity_main);
userName = (EditText) findViewById(R.id.edtUserName);
}else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.activity_main1);
userName = (EditText) findViewById(R.id.edtUserName);
}
// set username
userName.setText(storedUsername);
}
}