---
title: "Android中正确自适应屏幕翻转"
author: "leecong1p"
date: "2011-01-30T00:32:58Z"
tags: []
categories: ["移动开发"]
slug: "android"
draft: false
lastmod: "2011-01-30T00:37:02Z"
id: 899551
url: "https://leestorm.iteye.com/blog/899551"
---

大家都知道，很多Android手机带有重力感应传感器，能够对手机的翻转做出响应。比如应用在屏幕的自动翻转、重力感应游戏等方面。

      只要在androidmanifest.xml中对应的Activity中加入sensor属性即可实现屏幕自动翻转，如：

```
<
activity android:name=".demo"  
android:label="@string/app_name" 
android:screenOrientation="sensor"
>
```

   
      但是屏幕自动翻转也伴随着一个问题：当窗体切换或者布局切换时，Activity中OnCreate方法会被重复调用。一般OnCreate中会初始化一些数据，重复调用可能会产生意想不到的后果。解决方法如下：  
      在androidmanifest.xml中的activit元素加入configChanges这个属性，比如

```
<
activity android:name="demo" 
android:configChanges="orientation|keyboardHidden" 
android:label="@string/app_name"
>
```

   
      另外，在Activity的Java文件中重载onConfigurationChanged(Configuration newConfig)这个方法，这样就不会在布局切换或窗口切换时重载onCreate等方法。代码如下:

```
    public void onConfigurationChanged(Configuration newConfig)
    { 
        super.onConfigurationChanged(newConfig); 
        if (this.getResources().getConfiguration().orientation ==  Configuration.ORIENTATION_LANDSCAPE)
        {
            //TO-DO
        }
        else if (this.getResources().getConfiguration().orientation ==   Configuration.ORIENTATION_PORTRAIT)
        {
           //TO-DO
        }
    } 
```

 

      还有界面设计方面的问题，Android手机大部分是HVGA、WVGA的分辨率，屏幕视觉上比较“狭长”。往往竖着看很合适的布局，当屏幕横向翻转以后显示会变得很别扭。当屏幕由竖直方向改变为横向时，我们可以把界面中的控件由本来的垂直线性布局修改为横向线性布局，这样布局会更合理一些。我们可以自己写一个布局类集成LinearLayout布局，通过覆盖onMeasure方法来实现这种自动布局。当屏幕的宽高发生改变时，系统会调用onMeasure方法。通过这个方法，我们可以获得改变以后的宽高尺寸，从而来实现屏幕翻转的自动布局，主要代码如下：

```
    /**
     * 屏幕改变时自动调用
   * @param widthMeasureSpec 改变后的宽度
   * @param heightMeasureSpec 改变后的高度
   */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        /*宽度*/
        int screenWith = View.MeasureSpec.getSize(widthMeasureSpec);
        /*高度*/
        int screenHeight = View.MeasureSpec.getSize(heightMeasureSpec);
        
        /*竖直布局*/
        if (screenWith < screenHeight)
        {
            
            this.setOrientation(VERTICAL);
            for (int i = 0; i < getChildCount(); i++)
            {
                View childView = getChildAt(i);
                if (childView instanceof CakyCanvas)
                {
                    /*该控件占布局的2/5*/
                    LayoutParams params = new LayoutParams(screenWith,
                            screenHeight * 2/ 5
                    updateViewLayout(childView, params);
                }
                else if (childView instanceof CakyExplainCanvas)
                {
                    /*该控件占布局的3/5*/
                    LayoutParams params = new LayoutParams(screenWith,
                            screenHeight * 3/ 5
                    updateViewLayout(childView, params);
                }
            }
        }
        /*横向布局*/
        else
        {
            
            this.setOrientation(HORIZONTAL);
            for (int i = 0; i < getChildCount(); i++)
            {
                View childView = getChildAt(i);
                if (childView instanceof CakyCanvas)
                {
                    LayoutParams params = new LayoutParams(
                            screenWith * 2/ 5
                            screenHeight);
                    updateViewLayout(childView, params);
                }
                else if (childView instanceof CakyExplainCanvas)
                {
                    LayoutParams params = new LayoutParams(
                            screenWith * 3/ 5
                            screenHeight);
                    updateViewLayout(childView, params);
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
```