How to detect orientation change in layout in Android?

后端 未结 10 2321
挽巷
挽巷 2020-11-22 09:36

I just implemented a orientation change feature - e.g. when the layout changes from portrait to landscape (or vice versa). How can I detect when the orientation change event

10条回答
  •  暖寄归人
    2020-11-22 09:48

    Use the onConfigurationChanged method of Activity. See the following code:

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
    

    You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

    
    

    NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

    Hope this will help you... :)

提交回复
热议问题