[Reading Notes-Android game programming starts from scratch] 8. Common system controls for Android game development (FAQs about system controls)

Source: Internet
Author: User

Measurement Units commonly used in Android
Android sometimes requires some measurement units. For example, you may need to specify a specific unit in the Layout file.
Common measurement units include px, dip (dp), sp, and pt, in, and mm. The following describes the differences and connections between these units.
In: inch (length Unit );
Mm: mm (length Unit );
Pt: lb/point, 1/72 inch (a standard length Unit );
Sp: The full name is scaled pixels-best for text size, which is used to zoom in pixels and has nothing to do with the scale. It can be scaled Based on the font size, mainly used to process the font size;
Px: pixels in the screen;
Dip (dp): Independent pixel of the device, an abstract unit based on screen density. Because no device has different display effects, to solve the problem that the operation on a resolution-free mobile phone is not significantly different, a dip measurement unit is introduced, which has nothing to do with the hardware of mobile devices.

Density. Here is a brief introduction. The cell phone Density value (Density) indicates the number of display points per inch. There are two concepts related to the cell phone resolution, but the resolution and Density are correlated. The conversion formula is as follows:
The density value is 120, and the actual screen resolution is: 240px × 400px (two points correspond to one resolution );
The density is 160, and the actual screen resolution is 320px × 533px (three points correspond to two resolutions );
The density is 240, and the actual screen resolution is 480px × 800px (one point corresponds to one resolution ).

For example, the density of QVGA and WQVGA screens is 120, the density of HVGA screens is 160, and the density of WVGA screens is 240.

Res Resource Directory, because different running devices have different resource file directories. The real reason is that resource directories are divided based on different 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 introduction, dip (dp) should be used as the unit in layout; sp is recommended for defining the unit of text size.

 

Context
The Context class is an abstract class with many subclasses, such as Activity, TabActivity, and Service. In many methods, the Context parameter is required to be passed in for instance objects. For example, when a Toast instance object is used, the first object must be passed in the Context object. In fact, Context can be literally understood as a handle similar to the meaning of the Context. Because Activity is a subclass of Context, this can be used to replace Context in Activity, but if it is in the internal class (such as using the internal class to use the listening component ), you cannot use this instead of Context, but use "ActName. this ", ActName here refers to the Class Name of the Activity class.

In Android Context can have a lot of operations, but the main function is to load and access resources, specific can see the official documentation: http://developer.android.com/reference/android/content/Context.html

 

Resources and getResources
In Android resources, the corresponding static ID is automatically generated by the R. java Resource file and referenced by the ID generated by the R Resource file. In this way, when resources need to be modified, you do not need to modify them in the program source code. You can directly modify the resource files under the corresponding res.
In the source code, if you want to access the string variables defined in string. xml in the Resource Directory, you only need to reference them using getResources.
For example, to reference a string in string. xml, the variable "hello_world" is obtained as follows:

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

To reference an image named "goodby_times.png" in the drawable directory, use the following method:

getResources().getDrawable(R.drawable.goodby_times);

Of course, some functions support both the String type and the reference ID. For example, the setText () function in TextView supports not only the String type but also the ID parameter referenced by the R file. StrName in "R. string. strName" indicates the ID index generated by the string defined in string. xml in the R resource file.

 

FindViewById and LayoutInflater
LayoutInflater is similar to findViewById (). The difference between LayoutInflater and LayoutInflater is used to instantiate the layout in the xml layout file. findViewById, as its name suggests, is used to find the components defined in the xml layout file, such as EditText, TextView, And Button.
LayoutInflater can be used for instance layout in two ways:
1. Pass in the Context parameter to obtain the LayoutInflater instance, and then call the inflate function in the LayoutInflater class to obtain the layout instance.

LayoutInflater inflater = LayoutInflater.from(Context context) ;View view = inflater.inflate(R.layout.activity_main, null);

2. Obtain the LayoutInflater instance through the system service, and then call the inflate function in the LayoutInflater class to obtain the layout instance.

LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);View view = inflater.inflate(R.layout.activity_main, null);

Although the layout of instances is different, there is no difference in the nature of the two la S.

 

Redirect, exit, and pass data between multiple activities

 

Main Code:

Package yc. example. activityex; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. view. view; import android. view. view. onClickListener; import android. widget. button; public class MainActivity extends Activity implements OnClickListener {private Button btnOpen, btnHide, btnExit; // declaration Button private static String [] arrStr = new String [] {"has its own goals, then implement the language. "," The speed is faster than lightning, and even the shadows are blurred, such as the same group. "," There is only one thought in his mind: fast! Faster! Faster! "}; Private static int ARR_INT = 0; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // instantiate the Button btnOpen = (Button) this. findViewById (R. id. btnOpen); btnHide = (Button) this. findViewById (R. id. btnHide); btnExit = (Button) this. findViewById (R. id. btnExit); // Add the listener btnOpen to each button. setOnClickListener (this); btnHide. setO NClickListener (this); btnExit. setOnClickListener (this) ;}@ Override public void onClick (View v) {switch (v. getId () {case R. id. btnOpen: // create an Intent and set intent Intent = new Intent (MainActivity. this, OtherActivity. class); if (ARR_INT> = arrStr. length) ARR_INT = 0; // send data intent. putExtra ("info", arrStr [ARR_INT ++]); // start another Activity this. startActivity (intent); break; case R. id. btnHide :/** The finish () function indicates that the current Activity is exited. * Executing this function will call the onStop () and onDestory () functions in the life cycle, but this only pushes the current Activity to the background. * The resources in the program still exist, if the memory running on Android is not very tight, the program will not actually exit. */This. finish (); break; case R. id. btnExit:/** System. exit (0) function indicates to exit the current program. When Android * executes this function, the resources of this application will be recycled and the application will exit. */System. exit (0); // exit the program break ;}}}MainActivity. classpackage yc. example. activityex; import android. app. activity; import android. content. intent; import android. OS. bundle; import android. widget. textView; public class OtherActivity extends Activity {private TextView TV; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); TV = new TextView (this); setContentView (TV); // get the Intent intent Intent = this of the current Activity. getIntent (); // String info = intent. getStringExtra ("info"); // set the obtained data to TextView text TV. setText (info );}}OtherActivity. class

 

PS: Remember to declare the newly created Activity in the AndroidManifest. xml file. Otherwise, the application reports an exception because the Activity cannot be found.

<! -- Register the newly created Activity (OtherActivity) --> <activity android: name = "yc. example. activityex. OtherActivity"> </activity>

 

Three methods of screen Switching
When running applications on Android phones, users usually use portrait screens. However, if the mobile phone is suddenly landscape, it is likely to cause program exceptions, in Android, the current Activity is restarted every time the screen is switched. In this case, there are three solutions to the exception.

1. Lock switching between landscape and landscape screens
In this method, you only need to define the screen direction attribute of the Activity in the AndroidManifest. xml file to be either a horizontal screen or a vertical screen.
Set the screen to vertical display

<activity android:screenOrientation="portrait">

Set the screen to Landscape Display

<activity android:screenOrientation="landscape">

Other parameters:
"Unspecified": The default value is used by the system to determine the display direction. The determined policy is related to the device, so different devices have different display directions.
"Landscape": landscape Display (longer than width/height)
"Portrait": portrait display (height to width)
"User": the user's current preferred direction
"Behind": the direction of the Activity under the Activity is the same (in the Activity stack)
"Sensor": determined by physical sensors. If you rotate the device, the screen will be switched horizontally and vertically.
"Nosensor": Ignore the physical sensor so that it will not be changed as the user rotates the device (except for the "unspecified" setting ).

Because an Android Application may have multiple activities, you can configure the display mode of each Activity as needed. If this mode is not set, you can switch the display mode from portrait to portrait by default.

Or set the portrait screen in the source code:
Set portrait Screen

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Set landscape

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

2. process switching between landscape and landscape in source code
First, set the configChanges attribute for the Activity IN AndroidManifest. xml.

android:configChanges="orientation|screenSize"

Then, rewrite the onConfigurationChanged () function in the source code of the corresponding Activity. After this processing, when switching between the portrait and landscape screens, the onConfigurationChanged () function in the Activity will be responded, and then the landscape screen will be judged.

Package yc. example. helloworld; import android. app. activity; import android. content. res. configuration; import android. OS. bundle; import android. util. log; import android. widget. textView; public class MainActivity extends Activity {private TextView textView; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Log. I ("-- Main --", "onCreate"); textView = (TextView) findViewById (R. id. TV) ;}@ Override public void onConfigurationChanged (Configuration newConfig) {super. onConfigurationChanged (newConfig); Log. I ("-- Main --", "onConfigurationChanged"); if (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_PORTRAIT) {textView. setText ("current screen is portrait");} else if (this. getResources (). getConfiguration (). orientation = Configuration. ORIENTATION_LANDSCAPE) {textView. setText ("current screen is landscape ");}}}

This method will not restart the Activity by default when switching between landscape and landscape screens.

3. Rewrite the onRestoreInstanceState () and onSaveInstanceState () function code:

@Overrideprotected void onRestoreInstanceState(Bundle savedInstanceState) {super.onRestoreInstanceState(savedInstanceState);Log.i("YInfo", "onRestoreInstanceState()");}@Overrideprotected void onSaveInstanceState(Bundle outState) {super.onSaveInstanceState(outState);Log.i("YInfo", "onSaveInstanceState()");}

When switching between the screen and landscape, the system will respond to the onSaveInstanceState () function, restart loading the current Activity, and finally respond to the onRestoreInstanceState () function. Therefore, you can rewrite these two functions, processing when switching between the screen horizontal and vertical.

The preceding three screen switching modes are selected based on the current application.

Related Article

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.