"Reading notes-the zero-start of Android game programming" 8.Android game development Common system controls (System control FAQ)

Source: Internet
Author: User

Commonly used units of measurement in Android
Android sometimes requires some units of measurement, such as a specific unit that may need to be specified in the layout layouts file.
Commonly used units of measurement are: PX, dip (DP), SP, and some less commonly used PT, in, MM. Below is a detailed description of the differences and linkages between these units of measurement.
In: inches (length units);
MM: mm (unit of length);
PT: Lbs., 1/72 in. (a standard length unit);
SP: Full name scaled pixels-best for text size, magnification pixels, regardless of scale, can be scaled according to the user's font size, mainly used to handle the size of the font;
PX: pixels in the screen;
Dip (DP): device independent pixels, an abstract unit based on screen density, because there are different display effects in the device, so in order to solve the problem of running on the non-resolution mobile phone is not too large, the dip unit of measurement is introduced, which is independent of the mobile device hardware.

Speaking of density, here is a brief introduction. The cell phone density value (Density) indicates how many display points per inch, and the resolution of the phone is two concepts, but the resolution and density are interrelated, the conversion formula is:
The density value is 120, the screen actual resolution is: 240pxx400px (two points corresponds to a resolution);
The density value is 160, the screen actual resolution is: 320PXX533PX (3 points corresponding to two resolution);
The density value is 240, the screen actual resolution is: 480pxx800px (one point corresponds to a resolution).

For example, QVGA and WQVGA screen density value is 120,HVGA screen density value is 160,WVGA screen density value is 240.

Res resource directory, the corresponding resource file directory is different because of the different devices that are running. The real reason for this is that the resource directory is divided according to the difference in density:
The density value is 120, and the corresponding resource directory is drawable-ldpi;
The density value is 160, and the corresponding resource directory is drawable-mdpi;
The density value is 240, and the corresponding resource directory is drawable-hdpi.

According to the above, dip (DP) should be used as the unit in the layout, and SP is recommended for units defined as text size.

Context
The Context class is an abstract class with many subclasses, such as Activity, Tabactivity, Service, and so on. Many methods need to pass in the context parameter in order to instantiate an object, such as a Toast instance object, when the first object is passed into the context object. In fact, the context can literally be understood to resemble a handle to the meaning of the context. Because activity is a subclass of the context, it can be substituted with this when using context in the activity, but if you use this instead of the context in an inner class (such as using a listener component with an inner class), use the "Actname.this", where Actname refers to the class name of the Activity class.

The context in Android can be a lot of operations, but the main function is to load and access resources, you can see the official document:Http://developer.android.com/reference/android/ Content/context.html

Resources and Getresources
The corresponding static ID is automatically generated by the R.java resource file in the Android resource (Resource), which is referenced by the resource-generated ID from the R resource file. So when the resource needs to be modified, you do not have to go to the program source code modification, directly modify the corresponding res resource file.
In the source code, if you need to access the string variables defined in String.xml in the resource directory, you only need to refer to them by getresources.
For example, you need to refer to a string in String.xml whose variable is "Hello_world", obtained as follows:

Getresources (). getString (R.string.hello_world);

If you need to refer to a picture under the drawable directory named "Goodby_times.png", get the following method:

Getresources (). getdrawable (R.drawable.goodby_times);

Of course, some functions not only support incoming String types, they also support incoming reference IDs. For example, the SetText () function in TextView, which supports not only the incoming String type, but also the parameters of the R file reference ID. The strName in "R.string.strname" represents the corresponding ID index that is generated in the R resource file for the string defined in String.xml.

Findviewbyid and Layoutinflater
The Layoutinflater function is similar to Findviewbyid (), except that Layoutinflater is used to instantiate the layout in an XML layout file: And Findviewbyid, as the name implies, is found in the XML layout file by ID Defined components, such as EditText, TextView, Button, and so on.
There are two ways to use Layoutinflater for instance layout:
1. Obtain the Layoutinflater instance by passing in the Context parameter, and then call the inflate function in the Layoutinflater class to get the layout instance.

Layoutinflater inflater =null);

2. Get to the Layoutinflater instance through the system service and call the inflate function in the Layoutinflater class to get the layout instance.

Layoutinflater inflater =null);

Although the instance layout differs in form, the nature of the two layouts is not different.

Jump/exit/Pass data operations between multiple activity

Main code:

 PackageYc.example.activityex;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMainactivityextendsActivityImplementsOnclicklistener {PrivateButton Btnopen, Btnhide, Btnexit;//Claim Button    Private Staticstring[] Arrstr =NewString[] {"Have your own goal, then to achieve it, language is always pale." ",            "His speed is faster than lightning, even the shadow is blurred, like a tuanfeng." "In his mind, there is only one thought: Come on!" Just a little faster! Just a little faster! " }; Private Static intArr_int = 0; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); //Instantiate buttonBtnopen = (Button) This. Findviewbyid (R.id.btnopen); Btnhide= (Button) This. Findviewbyid (R.id.btnhide); Btnexit= (Button) This. Findviewbyid (R.id.btnexit); //add listeners to each buttonBtnopen.setonclicklistener ( This); Btnhide.setonclicklistener ( This); Btnexit.setonclicklistener ( This); } @Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btnopen://Create an intent and set the activity to be openedIntent Intent =NewIntent (mainactivity. This, Otheractivity.class); if(arr_int>=arrstr.length) Arr_int =0; //Send DataIntent.putextra ("info", arrstr[arr_int++]); //Start another activity             This. StartActivity (Intent);  Break;  CaseR.id.btnhide:/*The finish () function indicates exiting the current Activity. * Executing this function invokes the OnStop () and ondestory () functions in the life cycle, but this is just pushing the current Activity into the background, * The resources in the program still exist, and if Android runs memory is not very tense, the program is not really             Exit the. */             This. Finish ();  Break;  CaseR.id.btnexit:/** The System.exit (0) function indicates exiting the current program.             When Android * Executes to this function, the resources of this application will be recycled and exit the program. */System.exit (0);//Exit Program             Break; }    }}
Mainactivity.class
 PackageYc.example.activityex;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.widget.TextView; Public classOtheractivityextendsActivity {PrivateTextView TV; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); TV=NewTextView ( This);        Setcontentview (TV); //get the current Activity intentIntent Intent = This. Getintent (); //Get DataString info = Intent.getstringextra ("info"); //set the acquired data to TextView textTv.settext (info); }}
Otheractivity.class

PS: Remember to declare the new activity in the Androidmanifest.xml file, or the application will report an exception due to an activity not found.

<!---        <android:name = " Yc.example.activityex.OtherActivity "></activity>

Three ways to switch between the two screens
When running apps in Android phones, the average user is a vertical screen, but if you flip your phone sideways, it's likely to cause an exception, because every screen switch in Android will restart your current Activity. In this case, there are three ways to resolve the exception.

1. Lock and Shift screen
This method only needs to be in the Androidmanifest.xml file, define the screen orientation property for the Activity only for horizontal screen or vertical screen.
To pin the screen to a vertical display

<android:screenorientation= "Portrait">

To pin the screen to a horizontal screen display

<android:screenorientation= "Landscape">

Other 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).

Because there may be more than one activity in an Android application, you can configure the display of each activity as needed, and if not set, the default is to switch between the two screens.

or set the screen in the source code:
Setting up a vertical screen

Setrequestedorientation (activityinfo.screen_orientation_portrait);

Set Horizontal screen

Setrequestedorientation (Activityinfo.screen_orientation_landscape);

2. Handle the toggle event in the source code
First, set the Configchanges property for activity in Androidmanifest.xml

Android:configchanges= "Orientation|screensize"

Then rewrite the onconfigurationchanged () function in the corresponding Activity source code. When this is done, the onconfigurationchanged () function in the Activity is responded to when the screen is switched, and then the screen is judged and processed.

 PackageYc.example.helloworld;Importandroid.app.Activity;Importandroid.content.res.Configuration;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateTextView TextView; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);           Setcontentview (R.layout.activity_main); LOG.I ("--main--", "OnCreate"); TextView=(TextView) Findviewbyid (r.id.tv); } @Override Public voidonconfigurationchanged (Configuration newconfig) {Super. onconfigurationchanged (Newconfig); LOG.I ("--main--", "onconfigurationchanged"); if( This. Getresources (). GetConfiguration (). Orientation = =configuration.orientation_portrait) {Textview.settext ("Current screen is vertical screen"); } Else if( This. Getresources (). GetConfiguration (). Orientation = =Configuration.orientation_landscape) {Textview.settext ("Current screen is horizontal screen"); }    }}

In this way, the Activity is restarted by default when the screen is toggled.

3. Rewrite the onrestoreinstancestate () and onsaveinstancestate () function code:

@Override protected void onrestoreinstancestate (Bundle savedinstancestate) {super. Onrestoreinstancestate ( Savedinstancestate); LOG.I ("Yinfo", "Onrestoreinstancestate ()");} @Overrideprotectedvoid  onsaveinstancestate (Bundle outstate) {super . Onsaveinstancestate (outstate); LOG.I ("Yinfo", "Onsaveinstancestate ()");}

When the screen switches to the bottom screen, it responds to the Onsaveinstancestate () function, then restarts loading the current Activity and finally responds to the Onrestoreinstancestate () function, so you can override these two functions to The process of screen switching.

The above 3 kinds of processing of the screen switching mode, according to the current should be used to choose.

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.