Check orientation on Android phone

前端 未结 23 1966
庸人自扰
庸人自扰 2020-11-22 06:26

How can I check if the Android phone is in Landscape or Portrait?

23条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 06:54

    Here is code snippet demo how to get screen orientation was recommend by hackbod and Martijn:

    ❶ Trigger when change Orientation:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
            int nCurrentOrientation = _getScreenOrientation();
        _doSomeThingWhenChangeOrientation(nCurrentOrientation);
    }
    

    ❷ Get current orientation as hackbod recommend:

    private int _getScreenOrientation(){    
        return getResources().getConfiguration().orientation;
    }
    

    ❸There are alternative solution for get current screen orientation ❷ follow Martijn solution:

    private int _getScreenOrientation(){
            Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
            return display.getOrientation();
    }
    

    Note: I was try both implement ❷ & ❸, but on RealDevice (NexusOne SDK 2.3) Orientation it returns the wrong orientation.

    ★So i recommend to used solution ❷ to get Screen orientation which have more advantage: clearly, simple and work like a charm.

    ★Check carefully return of orientation to ensure correct as our expected (May be have limited depend on physical devices specification)

    Hope it help,

提交回复
热议问题