How screen changes from horizontally to vertically or Vice-versa automatically in Android
Hii
I want to know th开发者_Python百科e mechanism how the screen changes automatically from horizontally to vertically or vice-versa in android when we change the position of phone. Example in terms of coding would be highly appreciable.
Regards
Piyush
Screen is changed automatically from Portrait to Landscape and vice versa. So, in the most simple case you do not have to do anything. However, there is one important thing to take into account:
On orientation change, Android terminates your current activity and re-creates it again. So, if you have some important state variables, you must preserve them. In order to do that, you must override the function
@Override
public void onSaveInstanceState(Bundle stateToSave)
When instance is re-created, you have to check
@Override
public void onCreate(Bundle savedInstanceState)
value of savedInstanceState
. If it is null, it is first start. If it is not null, then it is re-creation caused by rotation, and you have to fetch state variable values from Bundle savedInstanceState
.
If you need different layouts for Portrait/Landscape please check answer from Anand.
If I understand correctly you're not asking how to change your own layout (the answer might be that you add a layout-land dir for you xml), or how to do some code on change of screen (the answer might be to use onConfigurationsChange), but you are asking how to accomplish the turning of the screen when the user turns the phone?
Well, then the answer is: The system does that, you don't have to do anything. It will do this automatically
I think you should do the following things:
1). Create folder name "layout-land" put all xml related to landscape into that which is similar name in "layout" folder for portrait.
2). Override the method onConfigurationChange in activity.
3). setcontentview(R.layout.layoutname).
4). in menifest <activity
android:name=".screenname"
android:configChanges="orientation"
>
</activity>
精彩评论