Android Orientation Change: Different Layout, Same Fragments -


this pretty classic android use case.

say have 2 fragments: fragmenta , fragmentb.

in landscape mode, fragmenta , fragmentb sit side side.

in portrait mode, each take full screen when in use.

(see image replace tablet->landscape , handset->portrait) different layout, same fragments on orientation change

as explained here (supporting single-pane , multi-pane layouts), there 2 ways achieve this:

1- multiple fragments, 1 activity: use 1 activity regardless of device size, decide @ runtime whether combine fragments in layout (to create multiple-pane design) or swap fragments (to create single-pane design).

2- multiple fragments, multiple activities: on tablet, place multiple fragments in 1 activity; on handset, use separate activities host each fragment. example, when tablet design uses 2 fragments in activity, use same activity handsets, supply alternative layout includes first fragment. when running on handset , need switch fragments (such when user selects item), start activity hosts second fragment.

this makes lot of sense in theory, i'm hitting hurdles in trying implement either of these approaches in way restores state of fragments when orientation changes , on button press.

i tried first approach , got quite far, found messy because required managing fragment transactions manually, in particular because container of fragment cannot changed easily. pain decide on pressed because last transaction on backstack might belong other orientation.

now trying second option. seems cleaner far fragments recreated scratch on every orientation change (because each orientation uses different activity). i have way restore fragment state other activity/orientation.

can explain how can done, or point me appropriate tutorial or sample application?

  • add configuration in mainactivity fragment replace <activity android:name=".mainactivity" android:configchanges="orientation|screensize|keyboard|keyboardhidden" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.default"/></intent-filter> </activity
  • you have create fragment landscape layout fragmenta , fragmentb enter image description here
  • if need change behavior of both fragment should change in onconfigurationchanged event of fragment.

@override public void onconfigurationchanged(configuration newconfig) { super.onconfigurationchanged(newconfig); if(newconfig.orientation == configuration.orientation_landscape) { //write stuff landscape orientation }else if(newconfig.orientation == configuration.orientation_portrait) { //write stuff portrait orientation } }


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -