In some scenarios, we need to change the screen direction of the mobile phone. Below is an example I wrote.
Xml page file:
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: paddingBottom = "@ dimen/activity_vertical_margin"
Android: paddingLeft = "@ dimen/activity_horizontal_margin"
Android: paddingRight = "@ dimen/activity_horizontal_margin"
Android: paddingTop = "@ dimen/activity_vertical_margin"
Tools: context = ". MainActivity">
Android: id = "@ + id/btn"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_alignParentLeft = "true"
Android: layout_alignParentTop = "true"
Android: text = "modifying the screen direction"/>
Page java file:
Package com. example. chcfg;
Import android. OS. Bundle;
Import android. app. Activity;
Import android. content. pm. ActivityInfo;
Import android. content. res. Configuration;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. Toast;
Public class MainActivityextends Activity {
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
Button btn = (Button) findViewById (R. id. btn );
Btn. setOnClickListener (new OnClickListener ()
{
Publicvoid onClick (View source ){
// TODO Auto-generated method stub
Configuration config = getResources (). getConfiguration ();
If (config. orientation = Configuration. ORIENTATION_LANDSCAPE)
{
// Set to portrait
MainActivity. this. setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_PORTRAIT );
}
// If the current screen is a portrait Screen
If (config. orientation = Configuration. ORIENTATION_PORTRAIT)
{
MainActivity. this. setRequestedOrientation (ActivityInfo. SCREEN_ORIENTATION_LANDSCAPE );
}
}
});
}
@ Override
Public void onConfigurationChanged (Configuration newConfig ){
// TODO Auto-generated method stub
Super. onConfigurationChanged (newConfig );
String screen = newConfig. orientation = Configuration. ORIENTATION_LANDSCAPE? "Horizontal screen": "portrait screen ";
Toast. makeText (this, "the direction of the System screen has changed \ n:" + screen, Toast. LENGTH_LONG). show ();
}
}
MainFest xml file:
Package = "com. example. chcfg"
Android: versionCode = "1"
Android: versionName = "1.0" type = "codeph" text = "/codeph">
Android: minSdkVersion = "8"
Android: targetSdkVersion = "18"/>
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
Android: name = "com. example. chcfg. MainActivity"
Android: label = "@ string/app_name"
Android: configChanges = "orientation">
If you have reprinted the results of your hard work, please indicate the source. Thank you.