Android Screen Toggle

Source: Internet
Author: User

One, the app is forbidden to switch between the screen and the inside

The above settings change the overall mobile phone screen switch, when the phone does not turn off the screen switch function, the system once triggered by the screen switch, the default state, the current active app interface will be the screen switch, due to the interface size of the screen and so on different parameters, A lot of software in the design and development in order to avoid the screen switching between the unnecessary trouble, usually need to let the app to disable the screen switch, this need to set up activity in the Androidmanifest.xml android: The Screenorientation property value to implement.

The Android:screenorientation attribute, he has the following several parameters:

"Unspecified": The default value is determined by the system to determine the direction of the display. The decision strategy is related to the device, so different devices will have different display directions.

"Landscape": Horizontal screen display (width ratio to long)

"Portrait": Vertical display (high width to long)

"User": the current preferred direction for users

"Behind": in the same direction as the activity below the activity (in the activity stack)

"Sensor": there is a physical sensor to decide. If the user rotates the device, the screen will switch between the screens.

"Nosensor": ignores the physical sensor so that it does not change as the user rotates the device (except for the "unspecified" setting).

such as the following settings

android:screenorientation= "Portrait"

Regardless of how the phone changes, the activity with this attribute will be displayed on the vertical screen.

android:screenorientation= "Landscape" for horizontal screen display.

The above modifications can also be set in Java code by code similar to the following

Setrequestedorientation (Activityinfo.screen_orientation_landscape)

Second, the app's screen switch can be manually triggered?

As described above, when the android:screenorientation is the default value "unspecified" or "sensor" and so on, there will be a system based on the rotation of the device to trigger the screen switch, So there is no way we manually trigger the change of the screen in the program, obviously the above is provided for us setrequestedorientation is a system provides a portal, below we give a key way to trigger the case column:

public class Mainactivity extends Activity implements Onclicklistener {

Private Button Mbtnlandscape;

Private Button mbtnportrait;

@Override

protected void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.activity_main);

Mbtnlandscape = (Button) Findviewbyid (R.id.but_landscape);

mbtnportrait = (Button) Findviewbyid (r.id.but_portrait);

Mbtnlandscape.setonclicklistener (this);

Mbtnportrait.setonclicklistener (this);

}

@Override

public void OnClick (View v) {

TODO auto-generated Method Stub

if (v = = Mbtnlandscape) {

Setrequestedorientation (Activityinfo.screen_orientation_landscape);

}else{

Setrequestedorientation (activityinfo.screen_orientation_portrait);

}

}

@Override

public void onconfigurationchanged (Configuration newconfig) {

Super.onconfigurationchanged (Newconfig);

String Message=newconfig.orientation==configuration.orientation_landscape? "Screen is set to: Horizontal screen": "Screen set to: Vertical screen";

Toast.maketext (this, message, Toast.length_long). Show ();

}

}

It is important to note that when manually invoked, ignoring the settings in Androidmanifest about Screenorientation, and the onconfigurationchanged in the above code to be called is also required, here, only to the code, not to discuss , and a supplementary explanation is given later.

Three, restart activity of the screen switch

In the above case, by default, the activity will re-invoke a round of onpause-> onstop-> every time the screen is toggled (including calls with Setrequestedorientation) ondestory-> The oncreate->onstart->onresume operation, which destroys the original activity object, creates a new activity object, because the software usually switches between the screen and the bottom, and the aspect of the interface is converted. Different layouts may be required. The specific layout switches can be implemented in the following two ways:

1) in the Res directory to establish the Layout-land and Layout-port directory, the corresponding layout file name is unchanged, such as Main.xml. Layout-land is a horizontal screen of the Layout,layout-port is the layout of the vertical screen, the other without the tube, the program itself will invoke the OnCreate method of activity, in order to automatically load the layout of the response according to the current screen situation.

2) If the layout resources are not the same as the above settings, you need to use Java code to determine whether the current horizontal screen or vertical screen and then to load the corresponding XML layout file (such as MAINP for vertical screen mainl for horizontal screen). Because when the screen changes to a horizontal screen, the system will re-call the current activity's OnCreate method, you can put the following methods in your oncreate to check the current direction, and then you can let your setcontentview to load different layout XML.

@Override

protected void OnCreate (Bundle icicle) {

Super.oncreate (Icicle);

int mcurrentorientation = Getresources (). GetConfiguration (). Orientation;

if (mcurrentorientation = = configuration.orientation_portrait) {

If Current Screens is portrait

LOG.I ("Info", "Portrait"); Vertical screen

Setcontentview (R.LAYOUT.MAINP);

} else if (mcurrentorientation = = Configuration.orientation_landscape) {

If Current screens is landscape

LOG.I ("info", "landscape"); Horizontal screen

Setcontentview (R.LAYOUT.MAINL);

}

Init ();//initialization, assignment, etc.

Findviews ();//Get control

Setlistensers ();//setting various monitoring methods for the control

}

The above is just a description of the layout switch, in fact, because the restart activity in the case of non-processing will inevitably lead to data loss and re-acquisition, so that the user experience is very poor. To do this, before switching to save the data, after switching the restart data recovery, the following steps:

Rewrite activity.onretainnonconfigurationinstance (), user save data before switching screen

@Override

Public Object onretainnonconfigurationinstance () {

Final myDataObject data = Collectmyloadeddata ();

return data;

}

Call Getlastnonconfigurationinstance () in the OnCreate () function to get the data saved by Onretainnonconfigurationinstance ()

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

Final myDataObject data = (mydataobject) getlastnonconfigurationinstance ();

if (data = = NULL) {

data = Loadmydata ();

}

...

}

Four, non-restart activity of the screen switch

While restarting activity gives us the means to save data and read data, it can be cumbersome to do so sometimes programmers don't want to restart the activity, and Android offers us a solution. is through the onconfigurationchanged intercept the screen transformation, so that the necessary re-layout and switching operations. The procedure is as follows:

First, the Android:configchanges attribute is set for the corresponding activity in manifest, so that the activity does not continue the above reconstruction process, as follows:

Andorid 3.2 Previous SDK can use the following configuration

Android:configchanges= "Orientation|keyboardhidden"

The SDK after Adnroid 3.2 must add a screensize attribute, as follows

Android:configchanges= "Keyboardhidden|orientation|screensize"

Or

Android:configchanges= "Orientation|screensize"

For a detailed description of the configchanges, there is a simple supplemental section behind it, which does not expand much.

Second, the current and the screen parameters are obtained in the onconfigurationchanged (Configuration newconfig) function of the activity or view. The order of invocation is similar to that of the touch event, but he does not have the concept of consuming events and will call each of the onconfigurationchanged functions sequentially. Here's an example of rewriting activity:

When the layout is main.xml with the same name in the Layout-land and Layout-port directories, respectively

@Override

public void onconfigurationchanged (Configuration newconfig) {

Super.onconfigurationchanged (Newconfig);

Setcontentview (R.layout.main);

Note that init () is removed here, otherwise it is initialized and the state is lost.

Findviews ();

Setlistensers ();

}

Layouts do not follow the Layout-land and Layout-port directories, while custom names

@Override

public void onconfigurationchanged (Configuration newconfig) {

Super.onconfigurationchanged (Newconfig);

int mcurrentorientation = Getresources (). GetConfiguration (). Orientation;

if (mcurrentorientation = = configuration.orientation_portrait) {

If Current Screens is portrait

Setcontentview (R.LAYOUT.MAINP);

Note that init () is removed here, otherwise it is initialized and the state is lost.

Findviews ();

Setlistensers ();

} else if (mcurrentorientation = = Configuration.orientation_landscape) {

If Current screens is landscape

Setcontentview (R.LAYOUT.MAINL);

Note that init () is removed here, otherwise it is initialized and the state is lost.

Findviews ();

Setlistensers ();

}

}

Of course, sometimes even if the layout does not have to change, you can directly to the original control to invoke the operation, such as:

public class Mainactivity extends Activity {

Private TextView TextView;

@Override

public void OnCreate (Bundle savedinstancestate) {

Super.oncreate (savedinstancestate);

Setcontentview (R.layout.main);

LOG.I ("--main--", "onCreate");

textview= (TextView) Findviewbyid (r.id.tv_id);

}

@Override

public void onconfigurationchanged (Configuration newconfig) {

Super.onconfigurationchanged (Newconfig);

LOG.I ("--main--", "onconfigurationchanged");

if (Newconfig.orientation==configuration.orientation_landscape) {

Textview.settext ("Current screen is horizontal screen");

}else{

Textview.settext ("Current screen is vertical screen");

}

}

}

It is important to note that the onconfigurationchanged function can only get the parameters after the screen switch, in which the new layout and the control's dimension position information is not obtained, and if the size and position information is to be processed, it must be called asynchronously or by the delay of the message. Here is the code for an app that needs to reset the Popupwindow location when switching between the two screens:

@Override

protected void onconfigurationchanged (Configuration newconfig) {

Super.onconfigurationchanged (Newconfig);

Do not create handler in view, you can call the post operation directly

New Handler (). postdelayed (New Runnable () {

@Override

public void Run () {

Updatepopup ();

//    }

}, 500);

Postdelayed (New Runnable () {

@Override

public void Run () {

Updatepopup (); //

}

}, 500);//If it is not in the post, it is called directly, then the popup position will be problematic

}

Although the explicit call to layout is not being re-laid out, the object of the control is not destroyed, but the control should be re-layout and measure, and then redrawn, if it is to be changed, otherwise the popup position change will not be raised, as for how to call the re-layout, The measure and draw operations are not much expanded here.

V. Additions to Androidmanifest.xml settings

Through the above code demonstration, we can see that the specific implementation involves the manifest project configuration within the specific activity of the screenorientation and configchanges two parameters, These two parameters Screenorientation priority is higher than configchanges, that is, if the screenorientation is set to fixed screen, then the configchanges parameter no matter how to set up a screen switch, Unless you manually call the Setrequestedorientation function in your code to modify it.

The Screenorientation property has been previously mentioned, and the About Configchanges property setting has the following options:

Value

Describe

Mcc

IMSI Mobile Station Country Code (MCC) changed--a SIM was detected and updated MCC

Mnc

IMSI Mobile Station Network Code (MNC) Changes--a SIM is detected and updated MNC

Locale

Area changes-The user selects a new language that the text needs to display

Touchscreen

The touchscreen has changed. (This usually does not happen.) )

Keyboard

The keyboard type has changed-for example, the user has plugged in an external keyboard.

Keyboardhidden

The accessibility of the keyboard changes-for example, the user discovers a hardware keyboard.

Navigation

The navigation type (trackball or Dpad) has changed. (This usually does not happen.) )

Screenlayout

Screen layout Changes-this causes different activity to be displayed.

Fontscale

The font scaling factor has changed-the user has selected a new font size.

Uimode

When the UI pattern changes-when the user places the device to the table or the car or the night mode changes, it can cause UI pattern changes. Read the Uimodemanager. Introduced at API Level 8 o'clock.

Orientation

The screen orientation changed-the user rotated the screen. Note: If the application's target API level is 13 or higher (through attribute minsdkversion and attribute targetsdkversion Declaration), you also need to declare the configuration item screensize, as this will change when the device chooses portrait and screen orientation.

ScreenSize

The currently available screen size is changed. This represents a change in the current available size, which is related to the current ratio, so when the user chooses a different picture and image, the change occurs. However, if your program target API level is 12 or lower, your activity will always handle this configuration change yourself (this change will not cause the activity to restart, even on Android 3.2 or newer devices). Added in API level 13.

Smallestscreensize

Changes in the physical screen size. No matter the direction of change, only in the actual physical screen packaging changes, such as: external display. The change in this configuration item causes a change in Smallestwidth configuration. However, if your program target API level is 12 or lower, your activity will handle the change yourself (this change will not cause the activity to restart, even on Android 3.2 or newer devices) at API level 13.

LayoutDirection

Layout direction changes. For example, writing from left-to-right (LTR) to right-to-left (RTL)

From the above table we can see in addition to the screen, including language, network, keyboard and peripheral changes can be monitored by the onconfigurationchanged function, the specific content and interpretation or view the official English documents, see the following links

Http://developer.android.com/guide/topics/manifest/activity-element.html

Chinese translation can be consulted http://wiki.eoe.cn/page/Activity.html

Combined with the online collation, summary of these configuration-related scenarios:

1, do not set the activity of the android:configchanges, the screen will recall the various life cycle, cut across the screen will be executed once, The vertical screen will be executed two times (I found on the Samsung 4.0 device screen and vertical screen is executed once, not said there are two times the case, do not know whether the previous version of the phone? );

2, set the activity of the android:configchanges= "orientation", the screen will still recall the various life cycle, cut horizontal, vertical screen will only be executed once;

3. When setting the activity's android:configchanges= "Orientation|keyboardhidden", the screen will not recall each life cycle, only the Onconfigurationchanged method will be executed.

Note: The above description is prior to Android3.2, if the Keyboardhidden option is missing, you cannot prevent the activity from destroying the restart, and you cannot execute the Onconfigurationchanged method. After 3.2, you must add the ScreenSize property to mask the life cycle of the call activity (I do not need to keyboardhidden on some devices, as long as screensize is possible, but for the sake of insurance or continue to keep Keyboardhidden bar).

Vi. Supplementary instructions for the Setrequestedorientation function

In the above (ii) for the manual trigger screen switching, we used the setrequestedorientation, then simply did the next demonstration, and later found that there is still need to do a supplementary explanation:

First in non-restart activity mode

After manually calling Setrequestedorientation, if it will trigger a portrait-to-landscape switch (that is, the request is inconsistent with the current screen and landscape, it will trigger a switchover), then the onconfigurationchanged function is called immediately The onconfigurationchanged function will not be called if it does not trigger a screen-to-line switch (consistent request).

This manual call to Setrequestedorientation can also be called anywhere in the activity, or in onconfigurationchanged, but once you've specified the transform as a horizontal or vertical screen, No matter how the screen changes in the back, it will no longer trigger the vertical screen switch, that is, the same as in manifest set the Android:screenorientation property for the horizontal screen or portrait screen. If you want to revert to a response to a screen with a physical sensor device transformation, then you need to manually invoke a code similar to the following to recover:

Setrequestedorientation (Activityinfo.screen_orientation_sensor);

Next in restart activity mode

Manually call setrequestedorientation after the screen setting request, if you need to switch between the screen (that is, the request before and after the screen state inconsistent), the activity will be destroyed and restarted; If you do not need to switch between the portrait and the The activity maintains the status quo unchanged;

Manually call Setrequestedorientation once, after completing the transformation, as in the above non-restart, the equivalent of setting the Android:screenorientation property in manifest as a horizontal or vertical screen. It is also necessary to recall a call similar to the above non-restart to restore.

Under such a principle, there is a solution to the following requirements:

Let the app start when the horizontal screen, the horizontal screen, the vertical screen of the vertical display, and then mobile phone switching screen can not use the How to solve it?

Online gave an example code, here do not do excerpt, interested can try, and then compare the implementation of others, see the following link

http://blog.csdn.net/yimo29/article/details/6030445

In addition to give a few I do collate reference post, think to me a great help, respectively, as follows

Android Horizontal screen vertical screen switching problem (a summary of the post, or good)

Http://blog.sina.com.cn/s/blog_77c632410101790w.html

Fixed screen switching (a real test summary) for Android phones

Http://www.cnblogs.com/zhangkai281/archive/2011/07/06/2099277.html

Android handles screen switching events

http://ipjmc.iteye.com/blog/1265991

Android Screen Toggle

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.