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:
- 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:
- Android will reset the ContentView when onConfigurationChanged (we can't see it anymore).
- We just prepare the layouts easily.
- Cons:
- 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:
- Add android:configChanged="orientation" of your activity.
- Now you can use onConfigurationChanged event.
- 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!
Comments
Post a Comment