部分网友会发现Activity在切换到后台或布局从横屏LANDSCAPE切换到PORTRAIT,会重新切换Activity会触发一次onCreate方法,我们可以在androidmanifest.xml中的activit元素加入这个属性Android:configChanges="orientation|keyboardHidden" 即可,比如

Java代码
复制代码 代码如下:
/* 声明Display对象,以取得屏幕宽高 */
final Display defaultDisplay = getWindow().getWindowManager()
.getDefaultDisplay();

intScreenH = defaultDisplay.getHeight();
intScreenW = defaultDisplay.getWidth();

/* 如果为Landscape */
if (intScreenW > intScreenH)
{
/* Landscape => Portrait */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else
{
/* Portrait => Landscape */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
/* 声明Display对象,以取得屏幕宽高 */
final Display defaultDisplay = getWindow().getWindowManager()
.getDefaultDisplay();
intScreenH = defaultDisplay.getHeight();
intScreenW = defaultDisplay.getWidth();
/* 如果为Landscape */
if (intScreenW > intScreenH)
{
/* Landscape => Portrait */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else
{
/* Portrait => Landscape */
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

同时在Activity的Java文件中重载onConfigurationChanged(Configuration newConfig)这个方法,这样就不会在布局切换或窗口切换时重载onCreate等方法。代码如下:
Java代码
复制代码 代码如下:
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
//land
}
else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
//port
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
{
//land
}
else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
{
//port
}
}

更多相关文章

  1. 解决Android手机 屏幕横竖屏切换
  2. Android(安卓)Preferences的使用
  3. Android中悬浮窗口的实现原理和示例代码
  4. android的应用包名与代码包名
  5. 利用wifi连接Android真机调试React Native代码
  6. Android(安卓)使用 Socket 连接阿里云服务器
  7. android sqllite数据库的多表联合查询
  8. Android(安卓)Studio使用JDBC连接MySQL出现java.lang.Unsupporte
  9. Android(安卓)studio 三个界面之间跳转程序代码

随机推荐

  1. 转载 Android(安卓)通过adb shell命令查
  2. android后台执行定时任务(保活)&&使用Alarm
  3. Android(安卓)ADB
  4. Android(安卓)webview监听网页对话框点击
  5. Android投票自定义View
  6. 【Android】Android(安卓)SurfaceFlinger
  7. 解析ANDROID ps命令执行后各项参数的含义
  8. Android实现定时刷新
  9. RN集成原生Android应用
  10. Android(安卓)虚拟机安装SD卡