Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Not Just Rotation: Configuration Changes on Android

Not Just Rotation: Configuration Changes on Android

Rotation changes aren't the only types of configuration changes you'll see in your Android apps. Let's look at what configurations are, and how to work with, or around, Activity restarts that result from configuration changes.

Lady Nicole

July 19, 2019
Tweet

Other Decks in Technology

Transcript

  1. What is a Configuration • Orientation • Screen width and

    height • Screen layout • Font Scale • Pixel Density • UI Mode
  2. Saving Instance State Pros: • Always works • Required for

    maintaining state Cons: • Limited State • Can be slow
  3. Cons: • Can't save data through process death Use a

    ViewModel Pros: • Unrestricted data • Fast updates
  4. Handling Configuration Changes class MainActivity : AppCompatActivity() {
 private val

    config = Configuration()
 override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 // Set the initial configuration.
 config.setTo(resources.configuration)
 // …
 }
 }
  5. Handling Configuration Changes override fun onConfigurationChanged(newConfig: Configuration) {
 super.onConfigurationChanged(newConfig)
 


    if (newConfig.screenLayout != config.screenLayout) {
 setContentView(R.layout.activity_main)
 
 val isToolBarShown = supportActionBar?.isShowing ?: true
 toolbar = findViewById(R.id.toolbar)
 setSupportActionBar(toolbar)
 if (!isToolBarShown) supportActionBar?.hide()
 }
 // Save new config
 config.setTo(newConfig)
 }
  6. Handling Configuration Changes override fun onConfigurationChanged(newConfig: Configuration) {
 super.onConfigurationChanged(newConfig)
 


    if (newConfig.screenLayout != config.screenLayout) {
 setContentView(R.layout.activity_main)
 
 val isToolBarShown = supportActionBar?.isShowing ?: true
 toolbar = findViewById(R.id.toolbar)
 setSupportActionBar(toolbar)
 if (!isToolBarShown) supportActionBar?.hide()
 }
 // Save new config
 config.setTo(newConfig)
 }
  7. Key Take-away Don't take for granted what can and cannot

    changes after your app has been launched. Anything can change.