× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How to change screen orientation in your code on Android

Victor Igbokwe
Nov 30, 2015
<p>Sometimes you may need to use different layouts on your app based on the current orientation. To do that you'll first need to get the current configuration, begin a fragment transaction and do a switch or if/else to know when to change your layout, like so:</p> <pre><code class="language-java">Configuration config = getResources().getConfiguration(); android.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); switch(config.orientation) { case Configuration.ORIENTATION_LANDSCAPE: // Device is now in landscape mode. MyLandscapeFragment fragment = new MyLandscapeFragment(); fragmentTransaction.replace(android.R.id.fragmentLayoutId, fragment); break; default: // Device is now in portrait mode. MyPortraitFragment fragment = new MyPortraitFragment(); fragmentTransaction.replace(android.R.id.fragmentLayoutId, fragment); break; } fragmentTransaction.commit();</code></pre> <p>And don't forget to commit your fragment transaction to complete the process.</p> <p>To finalize, update your AndroidManifest.xml file so your app can update the configuration at runtime when screen orientation changes occur.</p> <pre><code class="language-xml">&lt;activity android:name=".MyActivity" ... android:configChanges="orientation"&gt;</code></pre> <p>That's all folks! :)</p>
comments powered by Disqus