我正在建立我的第一个应用程序,几乎完成。(耶!)现在,我所要做的就是为onconfigurationchange设置java,当方向改变以及键盘被拉出时使用。
首先,问题是当方向改变时,由于setContentView方法放置了一个新布局,所有内容都会被删除。当然,这是有道理的,但是我想知道是否有任何方法或可能的解决方法,我可以让edittext和textview值在方向/键盘更改时保持不变。我尝试过各种方法,例如在setContentView之前获取字符串值,但是我发现这只会导致nullPointerException。
基本上,我试图保持edittext和textview将samne值作为方向或任何更改。
以下是我的代码摘要,以供参考
这不是真正的代码,只是我所做的一个总结。
public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//do some stuff that is the core of the app. Nothing that would impact this question though
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.landscape);
// same code that was within the onCreate. Just doing stuff related to my app
}if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.main);
// same code that was within the onCreate. Just doing stuff related to my app
}
}
' }
是的,我在我的AndroidManifest文件中写了
android:configChanges=“方向键盘隐藏”
应用程序的工作方式应该是,我只是没有文本Viwes和EditText正在更新。
谢谢!
最佳答案
您可以在savedInstanceState
中保存该值。
当您的活动开始停止时,系统将调用onSaveInstanceState()
,以便您的活动可以保存状态。
至于恢复值,可以使用
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
或
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
你也可以把你的布局放在potrait的
layout
文件夹和landscape的layout-land
文件夹中,这样你就不需要每次应用程序的活动都调用setContentView()
中的onConfigurationChanged()
。链接:activity recreating