Problems encountered in programming:
When creating a small music player, you want to automatically change the layout when switching between the horizontal and vertical screens.
Landscape screen:
Portrait screen: <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + pgltzybzcm9 "http://www.bkjia.com/uploadfile/Collfiles/20131228/2013122809122545.jpg" alt = "\">
You can create the layout_port and layout_land folders in the res folder (Note: Do not delete the layout files in the layout folder, and the layout file in the first two folders has the same name as that in layout .). In this way, the code in the Activity can be automatically converted to a horizontal or vertical screen without modification. However, this poses a problem. During each horizontal and vertical screen conversion, the system calls the onCreate () method to initialize the layout, which leads to some previous operations, information loss.
Solution:
After suffering from this problem, I went online to seek help. Finally found the solution: ① first in AndroidManifest. set activity attributes in xml: android: configChanges = "orientation | keyboard | keyboardHidden | screenSize" (Note: The screenSize attribute value in Versions later than android is indispensable ). ② Then add
The following method ------
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); }
After the above two steps are completed, the onCreate () method is not called by default in the case of screen switching, but the onConfigurationChanged method is executed by default.
The preceding steps prevent calling onCreate (), but the screen switching status and data loss may occur. A simple solution is as follows:
In the onConfigurationChanged method. The improved code is as follows:
public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig);if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { setContentView(R.layout.activity_main); findView(); setListener() } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { setContentView(R.layout.activity_main); findView(); setListener() }}
The findView () method is to re-obtain the View, and setListener () is to re-associate the listener. (The specific code will not be written ).