Friday, August 31, 2012

Change XML Layout automatically when orientation happens

Most of Android developers know that Android has lots of unique and useful features. One of them is changing the layout based on current orientation. But it seems that it is not easy to manage what to do before and after changing the layout.

Before manage/control the layout, you must have two layouts, landscape (in layout-land/ folder) and portrait (in layout/ folder).




Then, we start to manage/control the layouts.

If you don't want to manage/control all stuffs, just let Android do it for you, by doing:
  1. Remove android:configChanged="orientation" of your activity.
    • This will cause that you don't receive onConfigurationChanged event.
    • By doing this, there are some pros and cons:
      • Pros:
        1. Android will reset the ContentView when onConfigurationChanged (we can't see it anymore).
        2. We just prepare the layouts easily.
      • Cons:
        1. All parameters/properties will be reset when Android resets the ContentView.
In the first step, it is hard to maintain your layout, parameters, and other things you want to do when receiving onConfigurationChanged event. Therefore, we do all stuffs by doing:
  1. Add android:configChanged="orientation" of your activity.
    1. Now you can use onConfigurationChanged event.
  2. Inside onConfigurationChanged, do:
// Remove all views that you want to reuse in new layout
View myreuseview = findViewById(R.id.myReuseView);
findViewById(R.id.myLayout).removeAllViews;

// Reset the layout, your layout name is activity_layout.xml
// inside (in layout/ and layout-land/ folders).
setContentView(R.layout.activity_layout);

// Remove all views in new layout
findViewById(R.id.myLayout).removeAllViews;

// Add the reuse view to new layout
findViewById(R.id.myLayout).addView(myreuseview);

// do other initialization stuffs, like init buttons, etc.

In conclusion, it is better to control all your stuffs. It will give you a lot of advantages from memory control, reuse contents, etc.

Try it!

[ROM] Samsung S7 Stock Firmware BRI (Taiwan台灣)

Latest ROM: G930FXXU1DQEU Download: https://kfhost.net/tpl/firmwares.php?record=B7E6DE774E3811E7963AFA163EE8F90B Reference: http://...