![](/img/trans.png)
[英]How to handle Screen Orientation change in android without onConfigChanged
[英]How to handle screen orientation change
我正在尝试为我的Android应用程序处理屏幕方向更改,但没有成功。 这是我的清单:
<activity
android:name="fr.ups.l3info.l3info_catchgameactivity.CatchGameActivity"
android:label="@string/app_name"
android:screenOrientation="user"
android:configChanges="orientation|keyboardHidden" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
我在活动类中添加了此功能:
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
但是,当我更改屏幕方向时,将重新创建该应用程序,并且永远不会执行此功能。 我做错了什么? 谢谢你的帮助。
在清单清单android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection"
使用此android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection"
您可能想了解有关活动生命周期的更多信息。 您可以在此处找到更多信息( http://developer.android.com/training/basics/activity-lifecycle/index.html )
但更重要的是要熟悉您的活动状态 。
您要查找的方法不是onConfigurationChanged(Configuration newConfig)
,而是onSaveInstanceState(Bundle savedInstanceState)
。
现在,在您的OnCreate()
方法中,您需要检查是否已经保存了某些状态,然后重新创建该状态。
在此链接上有一个很好的解释: 使用“保存实例状态”保存Android活动状态
但基本上您需要做的是:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
然后考虑到这一点:
@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
}
...
}
STATE_SCORE
和STATE_LEVEL
是一些public static final String
值,用于以某种方式标记要保存的内容。
例如,如果您具有EditText视图,然后键入内容,然后旋转屏幕,则该值将丢失。 但是,在onSaveInstanceState()
方法中,应使用该Bundle
参数并将EditText视图的值作为String放置。
保存该内容后,现在您可以在onCreate()
方法中获取该值,并为其设置EditText视图的值。
希望这可以帮助 :)
如果您尝试在方向更改时为您的应用程序定义“不同的布局”,只需定义一个新的布局,使其名称与其他布局相同 ,然后将其置于res/layout-land
。
这样,当您的应用程序重新创建自己并在onCreate
函数中调用setContentView(layout_name)
,它将调用下res/layout-land
而不是下res/layout
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.