ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Mobile Application Development
    EC-333
    Progress0 / 33 topics
    Topics
    1. Mobiles Application Development Platform2. HTML5 for Mobiles3. Android OS: Architecture, Framework and Application Development4. iOS: Architecture, Framework5. Application Development with Windows Mobile6. Eclipse7. Fragments8. Calling Built-in Applications using Intents9. Displaying Notifications10. Components of a Screen11. Adapting to Display Orientation12. Managing Changes to Screen Orientation13. Utilizing the Action Bar14. Creating the User Interface15. Listening for UI Notifications16. Views17. User Preferences18. Persisting & Sharing Data19. Sending SMS Messages20. Getting Feedback21. Sending E-mail22. Displaying Maps23. Consuming Web Services Using HTTP24. Web Services: Accessing and Creating25. Threading26. Publishing Android Applications27. Deployment on App Stores28. Mobile Programming Languages29. Challenges with Mobility and Wireless Communication30. Location-aware Applications31. Performance/Power Tradeoffs32. Mobile Platform Constraints33. Emerging Technologies
    EC-333›Adapting to Display Orientation
    Mobile Application DevelopmentTopic 11 of 33

    Adapting to Display Orientation

    7 minread
    1,240words
    Intermediatelevel

    Adapting to Display Orientation in Mobile Applications

    Mobile applications need to function well across different screen orientations, including portrait (vertical) and landscape (horizontal). Users can rotate their devices at any time, and an app must adapt to provide a smooth, uninterrupted experience. If done correctly, this adaptability enhances usability and ensures that the app is accessible and functional in all orientations.


    Why Adapting to Display Orientation Matters

    • User Experience (UX): Users expect apps to look good and be usable, whether they hold their device vertically or horizontally. Ensuring smooth transitions and content adjustments improves user satisfaction.
    • Content Layout: Some types of content or interactions may work better in one orientation. For example, a video might look better in landscape mode, while a form might be more readable in portrait mode.
    • Performance: The app needs to efficiently manage different layouts and resources, ensuring the app performs optimally in any orientation.

    How to Handle Orientation Changes in Mobile Apps

    When the device orientation changes, the app's UI should adjust to accommodate the new screen dimensions. Here are the main steps and considerations for adapting to orientation changes:


    1. Detecting Orientation Changes

    • Android: Android provides built-in support to detect changes in screen orientation (portrait or landscape). The orientation change is automatically detected by the system, and the activity is typically restarted when the device orientation changes.

      • Using Configuration Changes: By default, an activity is restarted when the orientation changes. You can handle this change by overriding the onConfigurationChanged() method. For example:

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                // Handle landscape-specific actions
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
                // Handle portrait-specific actions
            }
        }
        
      • Prevent Activity Restart: If you don't want the activity to restart when orientation changes (which can be useful for maintaining state), you can declare it in the AndroidManifest.xml file:

        <activity android:name=".MainActivity"
                  android:configChanges="orientation|keyboardHidden">
        </activity>
        
    • iOS: In iOS, you can determine the orientation by checking the device’s orientation, and you can configure your app to support specific orientations.

      • Detecting Orientation Changes: iOS uses the UIDeviceOrientationDidChangeNotification to detect orientation changes. You can listen for this notification to handle the changes:

        NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
        
        @objc func orientationChanged() {
            if UIDevice.current.orientation.isLandscape {
                // Handle landscape mode
            } else if UIDevice.current.orientation.isPortrait {
                // Handle portrait mode
            }
        }
        
      • Allowing or Restricting Orientations: To specify the supported orientations, modify the Info.plist file:

        <key>UISupportedInterfaceOrientations</key>
        <array>
            <string>UIInterfaceOrientationPortrait</string>
            <string>UIInterfaceOrientationLandscapeLeft</string>
            <string>UIInterfaceOrientationLandscapeRight</string>
        </array>
        

    2. Adapting the Layout

    The UI components of the screen must adapt to the new orientation. Here’s how to adjust layouts effectively:

    Android:

    • Using Different Layout Resources: Android allows you to provide different layout resources for portrait and landscape modes. For example:

      • res/layout/activity_main.xml (for portrait)
      • res/layout-land/activity_main.xml (for landscape)

      When the orientation changes, Android will automatically use the appropriate layout resource based on the current orientation.

    • Handling Dynamic Layout Changes: Sometimes, the layout needs to be adjusted dynamically based on the current orientation. Use LinearLayout, RelativeLayout, or ConstraintLayout to create flexible layouts that can adjust automatically based on screen size or orientation.

    iOS:

    • Autolayout: iOS uses Auto Layout to create dynamic and responsive layouts. Auto Layout automatically adapts UI elements to the screen size and orientation.

      • You can use Stack Views to organize views, and these will automatically adapt based on orientation changes.
      • For complex layouts, use Constraints to define relationships between views and adjust them based on the available space.
    • Layout Adjustments: In some cases, you may need to manually adjust views when the orientation changes. For example, you could modify the layout in the viewWillTransition(to:with:) method:

      override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
          super.viewWillTransition(to: size, with: coordinator)
          // Handle layout changes based on new size or orientation
      }
      

    3. Handling Resources for Different Orientations

    You may want to display different resources (images, strings, etc.) based on the orientation. Here’s how to manage them:

    Android:

    • Resource Folders for Different Orientations: Android allows you to store resources that are specific to certain orientations or configurations.
      • For images, place different versions of the image for portrait and landscape in the following folders:
        • res/drawable-ldpi/
        • res/drawable-mdpi/
        • res/drawable-land/ (for landscape resources)
      • For specific layout resources, use res/layout-land/ for landscape layouts and res/layout/ for portrait layouts.

    iOS:

    • Images for Different Orientations: Use Asset Catalogs to provide different images for different screen orientations. You can set the specific images to be displayed in portrait or landscape mode.
    • Storyboards and Auto Layout: Auto Layout automatically adjusts constraints based on screen orientation. However, if specific images or assets are needed in different orientations, you can use size classes or specify different images for portrait and landscape in your assets catalog.

    4. Data Preservation During Orientation Changes

    When the orientation changes, it’s important to preserve the app’s state, such as user inputs or navigation data. You can achieve this in the following ways:

    Android:

    • Saving State with onSaveInstanceState(): If your activity is being destroyed and recreated due to an orientation change, you can save the state of UI elements or data in the onSaveInstanceState() method.
      @Override
      public void onSaveInstanceState(Bundle outState) {
          super.onSaveInstanceState(outState);
          outState.putString("username", usernameTextView.getText().toString());
      }
      
      @Override
      protected void onRestoreInstanceState(Bundle savedInstanceState) {
          super.onRestoreInstanceState(savedInstanceState);
          String username = savedInstanceState.getString("username");
          usernameTextView.setText(username);
      }
      

    iOS:

    • Preserving State with viewWillAppear: iOS provides methods like viewWillAppear and viewDidAppear to manage views and UI elements. You can store any necessary data in these methods to restore it after an orientation change.
    • State Restoration: iOS offers a built-in state restoration mechanism, where you can save and restore the app’s state automatically.

    5. Testing Orientation Changes

    Testing is crucial to ensure that your app behaves as expected when the orientation changes:

    • Test on Real Devices: Since orientation changes can behave differently on real devices compared to emulators, always test on physical devices.
    • Ensure Layout Responsiveness: Check that your app’s UI remains usable and visually appealing in both portrait and landscape orientations.

    Best Practices for Adapting to Display Orientation

    1. Design for Flexibility: Design your layouts to be flexible and responsive. Use relative positioning or constraint-based layouts to ensure the UI adapts smoothly.
    2. Minimize Disruption: Avoid disrupting the user’s experience when the orientation changes. For example, don’t restart the activity unnecessarily, and preserve user data.
    3. Use Auto Layout or Constraint Layout: Leverage Auto Layout (iOS) or ConstraintLayout (Android) to allow for automatic resizing and repositioning of UI components.
    4. Testing Across Devices: Ensure the app works across different screen sizes, orientations, and resolutions to provide a consistent experience.
    5. Prioritize Key Content: Some content might be more important in one orientation than another. Prioritize and adapt the layout to highlight the most crucial information in each mode.

    Conclusion

    Adapting to display orientation changes is a critical aspect of mobile app development. By ensuring your app can seamlessly transition between portrait and landscape orientations, you improve usability and enhance the user experience. With proper handling of layout resources, data preservation, and UI responsiveness, you can create an app that performs well on all devices and orientations.

    Previous topic 10
    Components of a Screen
    Next topic 12
    Managing Changes to Screen Orientation

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,240
      Code examples0
      DifficultyIntermediate