android

来源:互联网 发布:php宠物商城源代码 编辑:程序博客网 时间:2024/06/04 01:34
2795人阅读评论(1)收藏举报

  最近用到横竖屏切换的相关知识,大家也都知道横竖屏切换后Activity会重新执行onCreat函数。但是只要在Android工程的Mainfest.xml中

加入android:screenOrientation="user" android:configChanges="orientation|keyboardHidden"之后

[xhtml] view plaincopyprint?
  1.     <activityandroid:name=".MainActivity"android:label="@string/app_name" 
  2.     android:screenOrientation="user"android:configChanges="orientation|keyboardHidden"> 
  3.     <intent-filter> 
  4.         <actionandroid:name="android.intent.action.MAIN"/> 
  5.         <categoryandroid:name="android.intent.category.LAUNCHER"/> 
  6.     </intent-filter> 
  7. </activity> 

横竖屏切换之后就不会去执行OnCreat函数了,而是会去调用onConfigurationChanged()这样我们就能控制横竖屏的切换了。

当然你只想让它一直是横屏表示的话,只要设置android:screenOrientation="landscape"就行了。

但是如果我想让它启动的时候是什么横屏的话就横屏表示,纵屏的话就纵屏表示,然后手机切换横竖屏就不能用了该怎么解决呢?

首先: 在Mainfest.xml中追加android:screenOrientation="sensor" android:configChanges="orientation|keyboardHidden"

这两个属性。

第二步:取得屏幕的长和宽,进行比较设置横竖屏的变量。

[java] view plaincopyprint?
  1. Display display = getWindowManager().getDefaultDisplay(); 
  2. int width = display.getWidth(); 
  3. int height = display.getHeight(); 
  4. if (width > height) { 
  5.     orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
  6. } else
  7.     orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 

第三步:在onConfigurationChanged()函数中追加this.setRequestedOrientation(mOrientation)就行了

[java] view plaincopyprint?
  1. @Override 
  2. public void onConfigurationChanged(Configuration newConfig) { 
  3.     super.onConfigurationChanged(newConfig); 
  4.     this.setRequestedOrientation(mOrientation); 

但是这样的话你切到别的画面的时候再回到原画面,它就仍然是横的或者是纵的。怎么让它从别的屏幕回来后,又重新横竖屏布局呢?

只要在OnResume()中在设定下就行了。但是这个只支持横竖屏只有一个layout的。横竖屏分别对应layout的还不知道该怎么解决。

大家有什么想法的话可以留言。

[java] view plaincopyprint?
  1. @Override 
  2. protected void onResume() { 
  3.     mOrientation = ActivityInfo.SCREEN_ORIENTATION_USER; 
  4.     this.setRequestedOrientation(mOrientation); 
  5.     Display display = getWindowManager().getDefaultDisplay(); 
  6.     int width = display.getWidth(); 
  7.     int height = display.getHeight(); 
  8.     if (width > height) { 
  9.         mOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; 
  10.     } else
  11.         mOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; 
  12.     } 
  13.      
  14.     super.onResume(); 

原文地址:http://blog.csdn.net/yimo29/article/details/6030445

原创粉丝点击