Home > other >  How to use different design for landscape and portrait mode without recalling the API calls on that
How to use different design for landscape and portrait mode without recalling the API calls on that

Time:10-28

I have some API calls on my activity and different UI design for portrait and landscape mode.

I have added the below code in the manifest to avoid the activity recreation on mode change. But with the below code, will not support a different UI. So with this while changing the mode from one to another, the same UI will be displayed for both cases.

  android:configChanges="orientation|screenSize|keyboardHidden"

Tried by removing this code, then that UI is working as expected but activity is recreating on every rotation. I want to avoid that as well. Please suggest a better solution for this.

And my activity configure change is handled like below

 @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Checks the orientation of the screen


        if (getResources().getBoolean(R.bool.portrait_only)) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {


            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            }
        }
    }

CodePudding user response:

Put your landscape layout in

res/layout-land/

this will handle the layout when the screen is in a landscape mode.

And also use viewModel to deal with the configuration change, if you have any doubt on viewModel and how it works then visit this

How ViewModel survives configuration change

CodePudding user response:

When changing orientation by device rotation, the activity is destroyed and recreated. You cannot stop this. Although you can save the extra api calls everytime on orientation change by following any of the following -

  • Use ViewModel and LiveData. ViewModel survives orientation changes and is not recreated everytime during orientation changes, thus any data that needs to be saved across orientation changes should be kept in ViewModel. I would highly recommend going through app architecture guide to better understand and implement the correct architecture for you application.
  • If you don't want to implement above and/or are looking for a quick solution, you can save you data in Bundle by overriding onSaveInstanceState method and restore it by overriding onRestoreInstanceState.But if your api response is very big, I would not suggest this.

I would suggest you to follow the first point as it would be the best way to get around your use case.

  • Related