如何防止我的android应用程序在锁定屏幕的屏幕方向发生变化时崩溃?
我最近发现了这个问题。 我正在使用三星Tab 7''和安卓4.1进行测试 我有一个新的android应用程序项目。 这里是trash.xml如何防止我的android应用程序在锁定屏幕的屏幕方向发生变化时崩溃?,android,locking,screen,orientation,collapse,Android,Locking,Screen,Orientation,Collapse,我最近发现了这个问题。 我正在使用三星Tab 7''和安卓4.1进行测试 我有一个新的android应用程序项目。 这里是trash.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_hei
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>
到目前为止相当简单。然后我将此代码放在AndroidManifest的MainActivity选项卡中:
android:screenOrientation="portrait"
当我:
1.锁定屏幕
2.将平板电脑的方向更改为横向
3.然后打开屏幕
4.让我惊讶的是,我的应用程序并没有返回到纵向,而是因为一个简单的错误而崩溃了(参考资料$NotFoundException):
如何避免此问题,而不是为我的应用程序创建横向布局?您可以尝试调用
setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Graphic)
在activites onCreate()中,您的项目必须以3.0或更高版本为目标;
2在您的活动选项卡(android清单)中,您必须添加以下两行:
3在活动类中,添加以下方法:
这个是这样工作的。将configChanges添加到“活动”选项卡将使每次在横向和protrait之间更改屏幕时调用onConfigurationChanged方法,反之亦然。然后,在该方法中,我们使用setRequestOrientation强制活动保持特定的方向
android:screenOrientation="portrait"
06-15 00:12:37.390: E/AndroidRuntime(6452): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.trash/com.example.trash.MainActivity}: android.content.res.Resources$NotFoundException: Resource ID #0x7f030001
android:screenOrientation="portrait" or android:screenOrientation="landscape"
android:configChanges="orientation|screenSize"
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}