Android Study Notes (): switching between landscape and landscape screens

Source: Internet
Author: User

1. Prepare the environment

For the simulator, you only need to press Ctrl + F12 to switch between the portrait screen (portrait) and landscape screen (landscape.


2. UI screen switching implementation

The following is a simple example ,.

We need to write two Android XML files. Assume the file is chapter_19_test1.xml and put it in the regular directory location layout/the content is as follows:

<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="fill_parent"  android:layout_height="fill_parent"><Button android:id="@+id/c19_pick"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:layout_weight="1"  android:text="Pick"  android:enabled="true" /><Button android:id="@+id/c19_view"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:layout_weight="1"  android:text="View"  android:enabled="false" />  </LinearLayout>

The other is located under the layout-land/directory. The file name is the same. Here is the layout of landsapce. in simple words, we only make a few changes to set android: orientation = "vertical ", change to android: orientation = "horizontal.


3. What happened during switchover

Is it so easy? On Android, the layout widget automatically rotates the screen based on your xml file and selects the correct xml file for layout. Intelligent, right? Yes, but that's all. Let's make an experiment: Based on the xml above, every time you press the pick button, the counter testNum is added. To make it intuitive and simple, the value of testNum is passed through System. print out and display it directly on the Button. The test code is as follows:

Public class chapter19test1 extends activity {private int testnum = 0; // experiment: Tracking testnum @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. chapter_19_test1); button pickbutton = (button) findviewbyid (R. id. c19_pick); pickbutton. settext ("pick:" + testnum); pickbutton. setonclicklistener (new view. onclicklistener () {/* press the pick button each time. The counter is testnum. Add */Public void onclick (view v) {testnum ++; system. out. println ("pick:" + testnum); (button) V ). settext ("pick:" + testnum) ;}}); viewbutton. setenabled (contact! = NULL );}}

When we press the pick button in the portrait screen, three times, and then press Ctrl + F12 from the portrait screen to the landscape screen, we find that testnum does not follow it, continue counting, but re-start computing, and we hope to keep the original shape. During screen switching, Android willDestroy and re-create our activity. This means that you need to save your data and restore the status from the saved data during switchover..


4. Save data

We use onsaveinstancestate () to save data. Because it is re-create, oncreate () is triggered during screen conversion, and data can be restored in onrestoreinstancestate.

Protected void onCreate (Bundle savedInstanceState ){...... button pickButton = (Button) findViewById (R. id. c19_pick);/* obtain the stored data from the Bundle and restore it */if (savedInstanceState! = Null) {testNum = savedInstanceState. getInt ("count");} pickButton. setText ("Pick:" + testNum); pickButton. setOnClickListener (new View. onClickListener (){......});} @ Override/* store data through onSaveInstanceState (), such as in Bundle. */Protected void onSaveInstanceState (Bundle outState) {// TODO Auto-generated method stubsuper. onSaveInstanceState (outState); outState. putInt ("count", testNum );}

5. An interesting example

In the above example, we press the pick button to enter the contact list in Intent mode, select a contact in the list, and return. By calling startActivityForResult, we can obtain the return value. Click View to display the details of the contact. In this example, we will learn the following:
1) how to call the contact list new Intent (Intent. ACTION_PICK, ContactsContract. Contacts. CONTENT_URI);, How to call to view the details of a contact new Intent (Intent. ACTION_VIEW, contact)
2) how to call the returned intent: startActivityForResult (intent, requestCode );
3) During screen switching, review and save the data (contact) and restore the original status.It is worth noting that the following processing is not only for horizontal and vertical screen, but also for other restoration, such as activity close caused by too low battery energy.

Public class Chapter19Test1 extends Activity {static final int PICK_REQUEST = 1000; private Button viewButton = null; private Uri contact = null; protected void onCreate (Bundle savedInstanceState ){...... pickButton. setOnClickListener (new View. onClickListener () {/* next to 1) how to call the contact list; 2) how to call the intent */public void onClick (View v) of the return value) {Intent intent = new Intent (Intent. ACTION_PICK, ContactsContract. contact S. CONTENT_URI); startActivityForResult (intent, PICK_REQUEST) ;}}); viewButton. setOnClickListener (new View. onClickListener () {/* 1) how to call to display details of a contact */public void onClick (View v) {startActivity (new Intent (Intent. ACTION_VIEW, contact) ;}}); restoreMe (savedInstanceState); viewButton. setEnabled (contact! = Null) ;}@ Override/* 2) how to obtain the intent return value and determine whether we need the */protected void onActivityResult (int requestCode, int resultCode, intent data) {super. onActivityResult (requestCode, resultCode, data); if (requestCode = PICK_REQUEST) {if (resultCode = RESULT_ OK) {contact = data. getData (); viewButton. setEnabled (true) ;}}@ Override/* 3) is used to save data in situations such as screen rotation, which is automatically called by the system. */Protected void onSaveInstanceState (Bundle outState) {super. onSaveInstanceState (outState); if (contact! = Null) {outState. putString ("contact", contact. toString () ;}}/* 3) called in onCreate. Data is restored when it is rotated with the screen. In fact, there are other situations, for example, the battery power is too low */private void restoreMe (Bundle state) {contact = null; if (state! = Null) {String contactUri = state. getString ("contact"); if (contactUri! = Null) {contact = Uri. parse (contactUri );}}}}

6. Restrictions and Replacement Methods for saving data with onSaveInstanceState ()

In this example, onSaveInstanceState () is used to save data. This call is not only used to switch between the portrait and landscape screens, but also to handle other interruptions, such as low memory, therefore, data storage is not only serialized but also independent of the currently executed process. The limitation is that it can only be saved through bundle.

In some activty cases, this process is okay, but in other cases, such as online chat, we cannot save the object (such as socket) through bundle, it makes no sense to only store the socket information (IP address and port), that is, switching between the landscape screen and the portrait screen will lead to disconnection and reconnection. Obviously it is not what we expect.

The solution is to replace onSaveInstanceState () with onRetainNonConfigurationInstance (). Use it to save the object and get it through getLastNonConfigurationInstance. In this way, we can save socket, thread, and so on. The preceding example can be revised as follows:

Public class Chapter19Test2 extends Activity {...... @ Overrideprotected void onCreate (Bundle savedInstanceState ){...... /* recover data */restoreMe ();......}...... @ Override/* use onRetainNonConfigurationInstance () to directly Save the object. In the previous example, the Uri's toString () information is saved */public Object onRetainNonConfigurationInstance () {return contact ;} /* recover data and directly obtain the object */private void restoreMe () {contact = null; if (getLastNonConfigurationInstanc E ()! = Null) {contact = (Uri) getLastNonConfigurationInstance ();}}}

Related links:
My Android development articles

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.