7

你会认为会有一个直截了当的解决方案。Android 文档状态:

方向传感器在 Android 2.2(API 级别 8)中已弃用。我们建议您将 getRotationMatrix() 方法与 getOrientation() 方法结合使用来计算方向值,而不是使用来自方向传感器的原始数据。

然而,他们没有提供关于如何实施getOrientation()getRotationMatrix(). 我花了几个小时阅读这里关于使用这些方法的开发人员的帖子,但他们都有部分粘贴的代码或一些奇怪的实现。谷歌搜索没有提供教程。有人可以使用这两种方法粘贴一个简单的解决方案来生成方向吗?

4

3 回答 3

6

这是以下的实现getOrientation()

public int getscrOrientation()
    {
        Display getOrient = getWindowManager().getDefaultDisplay();

        int orientation = getOrient.getOrientation();

        // Sometimes you may get undefined orientation Value is 0
        // simple logic solves the problem compare the screen
        // X,Y Co-ordinates and determine the Orientation in such cases
        if(orientation==Configuration.ORIENTATION_UNDEFINED){

            Configuration config = getResources().getConfiguration();
            orientation = config.orientation;

            if(orientation==Configuration.ORIENTATION_UNDEFINED){
                //if height and widht of screen are equal then
                // it is square orientation
                if(getOrient.getWidth()==getOrient.getHeight()){
                    orientation = Configuration.ORIENTATION_SQUARE;
                }else{ //if widht is less than height than it is portrait
                    if(getOrient.getWidth() < getOrient.getHeight()){
                        orientation = Configuration.ORIENTATION_PORTRAIT;
                    }else{ // if it is not any of the above it will definitely be landscape
                        orientation = Configuration.ORIENTATION_LANDSCAPE;
                    }
                }
            }
        }
        return orientation; // return value 1 is portrait and 2 is Landscape Mode
    }

你也可以参考这个例子,它代表了这两种方法的使用:

     getOrientation and getRotationMatrix

http://www.codingforandroid.com/2011/01/using-orientation-sensors-simple.html

于 2013-02-19T11:25:23.880 回答
4
 public int getScreenOrientation() {


// Query what the orientation currently really is.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)                {
    return 1; // Portrait Mode

}else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    return 2;   // Landscape mode
}
return 0;
}
于 2014-01-09T09:14:50.453 回答
2
protected void onResume() {
    // change the screen orientation
    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        setContentView(R.layout.portrait);
    } else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setContentView(R.layout.landscape);
    } else {
        setContentView(R.layout.oops);
    }
}
于 2014-01-23T19:02:17.003 回答