How to detect landscape left (normal) vs landscape right (reverse) with support for naturally landscape devices?

前端 未结 2 716
南旧
南旧 2020-12-19 00:18

What I would like to do:

  • Detect the current layout orientation of the device (Portrait, Landscape-Left, Portrait(upside down), Landscape-Right)
  • Differ
相关标签:
2条回答
  • 2020-12-19 01:06

    Right landscape wasn't supported till 2.2. You'll need to have <2.2 devices choose in the options or something.

    0 讨论(0)
  • 2020-12-19 01:13

    The only way I managed to overcome this (Without going to API 8) is by registering to the SensorManager (Sensor.TYPE_ACCELEROMETER) and get onSensorChanged events.

    I noticed that when your screen is in landscape mode, you will get close values to -9 (g) or +9 (g) on the latheral (x) axis. you can just check for positive or negative, but you need to save the state in the case the device is put back on the table with face upwards

    Your code (snippet) should roughly look like that:

    private float mShiftAngle = 0;
    
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            aValues = event.values; 
            int deviceRot = getResources().getConfiguration().orientation; 
            if (deviceRot == Configuration.ORIENTATION_LANDSCAPE) {
                if (Math.abs(aValues[0])>4)
                    mShiftAngle = (aValues[0]>0 ? 90 : -90);
            }
            else 
                mShiftAngle = 0;       
        }
    }
    

    it helped me, hope this will help you.

    0 讨论(0)
提交回复
热议问题