Android开发疑问:已通过Manifest配置屏幕旋转,为何仍需关注该问题?
android:configChanges="orientation|screenSize" Prevents Activity Recreation? Great question! It’s totally understandable to wonder why we’d bother with orientation handling when that manifest flag seems to “solve” the problem in one line. Let’s break down the key reasons this isn’t a one-size-fits-all fix:
You might need orientation-specific UI/resource changes
A lot of apps have different layouts (or resources like images, strings, or dimension values) for portrait vs landscape. When you useconfigChanges, the system skips automatically loading the corresponding resources (like layouts fromlayout-land/). You’d have to manually listen for orientation shifts, detect the new orientation, and swap out layouts/resources yourself—this adds way more code complexity than letting the system handle recreation and resource loading natively.System-managed state recovery is skipped
When an Activity is recreated normally, the system handles saving and restoring certain states automatically: things like View focus, input method state, Fragment back stacks, and even instance state you save viaonSaveInstanceState(). If you disable recreation, you lose this built-in safety net. You’ll have to manually track and restore all these states, which is easy to mess up (and easy to forget edge cases like partial screen rotations on foldables).It’s not future-proof or universally compatible
The Android framework keeps evolving—think foldables, foldable states, or new configuration changes that might affect your app. Theorientation|screenSizeflags don’t cover every possible configuration shift. Using this workaround now could lead to unexpected bugs down the line when new device types or system versions come out. Plus, other developers working on your code might not realize why the Activity isn’t recreating, making maintenance harder.It’s an anti-pattern for most use cases
Android’s default recreation behavior is designed to ensure your app adapts properly to configuration changes. Bypassing it withconfigChangesis meant for very specific scenarios (like full-screen games or video players where recreation would disrupt the user experience), not as a general solution. For most apps, properly implementing state saving/restoration makes your code more robust, testable, and aligned with platform best practices.
So in short: that manifest flag is a quick band-aid for specific cases, but for most apps, investing in proper orientation change handling (via onSaveInstanceState, ViewModel, or other state-preservation patterns) is the better long-term approach.
内容的提问来源于stack exchange,提问作者user9609225

