Basic structure of Android project detailed _android

Source: Internet
Author: User
Tags bit set map class modifiers naming convention unique id

First, Introduction

The 3rd Chapter although through Baidu Map application shows you may be interested in content, but, if you are a beginner, at the beginning to understand and understand the code can be very laborious. To address this issue, starting with this chapter, this module will begin with the basics and take you step-by-Step into a paradise for Android application development in C #.

Second, Androidapp entrance

To develop an Android application in C #, you first need to have a perceptual knowledge of the basic structure of the project. As shown in the following illustration:

The Android app uses a single portal, and the source program doesn't see where the program starts, and when the app is loaded into memory, the Android operating system automatically starts running the application from the internal custom entrance. This unique architecture allows programmers to design code that interacts directly with the Android operating system, but its drawbacks are obvious: even a very simple program can become complex.

To facilitate locating the program entry point, when a new Android project is created, by default the program is executed from this activity by means of "Mainlauncher = True" in the attribute declaration of the MainActivity.cs file:

[Activity (Label = "Mydemos", Mainlauncher = True)]

public class Mainactivity:activity

{

......

}

Note the prefix of the MainActivity.cs, which generally means that it controls the layout file Main.axml (but not necessarily). Like what If you change the main.axml to First.axml, then it is best to name the activity class FirstActivity.cs, in other words, the prefix is only to facilitate the viewing of its interface with the corresponding relationship, this is only a naming convention, rather than the inevitable requirements of file naming.

In fact, you can put "Mainlauncher = true" into any class that inherits from the activity. In summary, the program starts from which activity you put into the attribute declaration of which class.

Iii. Resource Documents (various documents under the Resources folder)

A resource file is an attached file that is used in code and packaged into an application at compile time. Depending on the type of resource, these files are saved in different folders in the project.

Under the Resources folder for your project, you can divide it into subfolders, depending on the type of resource. These resources include pictures, audio files, and anything that is relevant to the visible content of the program. For example, custom animations, menus, styles, colors, and the layout of user interaction pages that are described by the. axml file (with the design interface) or the. xml file (without the design interface).

1. Basic Concepts

Resources saved under the Resource folder do not include code files, but rather files that are compiled and packaged with projects other than code files, such as sounds, videos, images, strings, layout files, and so on.

The advantage of organizing resources separately is that code separation can be applied to multiple platforms, and can be checked at compile time and provide smart hints for typing C # code after the compilation passes.

Using resources makes it easy to modify the characteristics of a program without having to modify the code. And through an optional collection of resources, you can configure the optimizer for different devices (for example, different national languages and different screen sizes, and so on).

The System build tool automatically defines a unique integer ID for each resource used by the Android project, and the program uses the ID to obtain a reference to the resource in the code or to other resources in the. xml or. axml. For example, the program contains a picture file called Logo.png (saved in the resources/drawable/directory), and the tool generates a resource ID called Resource.drawable.logo, which can be used to refer to the picture in the program.

An important ability to separate resources is to provide alternative resource files for different device configurations. For example, if you define a UI string in XML, you can translate the strings into other national languages and save them separately in separate files. The Android system then provides the appropriate national language string into the UI based on the national language modifiers appended to the resource directory name (for example, res/values-fr/is the value of the French string) and the user's settings for the national language.

Android supports a number of different modifiers to support optional resources. These modifiers are short strings that are added to the resource directory name. This definition is intended to define the specific configuration of the device to ensure that resources under this directory may be used.

2, the Basic Resources folder

The basic resource folder is used to save the frequently used resource files in your project.

(1) Drawable folder

Drawable folder: Save the generic picture file.

drawable Resources is an image resource that is compiled into an application that can invoke or reference other XML resources through the API. For example, bitmap files (. png,. gif,. jpg), resizable 9-patch-formatted images, a list of states defined in an XML file, a generic shape definition 、...... Wait

Obtain these file resources under this folder by Resources.drawable.

Description: The meaning and usage of 9-patch image (*.9.png) See examples of images described in chapter 5th of this blog.

(2) Other picture resource folders corresponding to the resolution

Other related folders that correspond to resolution are:

drawable-ldpi folder: Save image files for low resolution mobile phone.

drawable-mdpi folder: Save image files for medium resolution mobile phone.

drawable-hdpi folder: Save image files for high resolution mobile phone.

drawable-xdpi folder: Save image files for ultra high resolution mobile phone.

drawable-xxdpi folder: Save image files for super high resolution mobile phone.

(3) Layout folder

The layout folder is used to save all the interface files (including the. axml file with the design interface and the. xml file without the design interface), and if you are happy, you can change. xml to. Axml at any time, or you may change the. Axml name to. Xml.

Generally use Main.axml as the default app home layout file, with design and source two modes.

The files under this folder are XML files that can be compiled into screen layouts and can be obtained by resources.layout to obtain the resources defined by IDs in these files by Resources.id.

(4) Values folder

The values folder holds XML files that are described in strings that contain one or more simple string-type values or lists (strings, integers, colors, and so on). For example, in an XML file, define a series of colors with a string list.

Values folder resource files are text resources, and there are some convention file names in the folder. In addition, the values in the XML file in the directory can define multiple resources rather than only individual resources, for example:

String.xml: The list of string values is saved, and these resources are obtained by resources.string. Colors.xml: Saves the list of color values and obtains these resources through Resources.color. Arrays.xml: Defines an array that gets these resources through Resources.array. Dimens.xml: Preserve the scale values and obtain these resources through Resources.dimens.

(5) Animator folder

The folder is saved with an XML file that animates the animated description of the object with the attribute. Similar to WPF's property animations, its usage is a very flexible and powerful way to describe animations that describe various types of objects.

The "Property animation" is provided at API level (Android 3.0).

Note: Android's attribute animation is very similar to the use of WPF's property animation, as long as you learn one of them, it will soon be another use.

(6) Anim folder

This folder is used to save the XML file that describes the motion tween (tween animations).

A motion tween uses a series of animated instructions to perform a transformation on the contents of a View object, which is used to convert the Views object to an animation, such as an edge rotation that increases the size of the image or text.

Because rotating an image or text results in a rapid expansion of the capacity occupied, motion tweens can only be used for view objects.

(7) Color folder

This folder is used to save an XML file that describes a list of color states. The color status list refers to the change of each state by color, such as button press, disable, and so on. To make a change in the color of the button as the state changes, you need to define a list of color status columns that describe the changes in the color states.

(8) Menu folder

This folder holds the XML file that describes the menu, such as the Application Options menu, pop-up menu, Context menu (shortcut menu), submenu, and so on.

Obtain these file resources under this folder by Resources.menu.

(9) Raw folder

Any file saved in the original binary form. These files are still compiled into the Android application in the form of a binary file.

You can obtain these file resources under this folder by Resources.raw.

(Ten) XML folder

The XML file saved under this folder is similar to a. NET configuration file, that is, any XML file that can be read by an application at run time is saved under that folder.

Obtain these resources through Resources.xml.

4, the way of referencing resources

When you add a resource file to a project, the pipeline automatically adds the resource description to the resource and automatically generates the corresponding class (saved in the Resource.designer.cs file), and the Auto-generated class automatically assigns a unique ID to each resource.

There are two ways to access and manage resources:

-----Reference Resources in C # code.

-----reference resources in the. xml or. axml layout file.

(1) Way 1--referencing resources in C # code

Format: @[<packagename>.] Resource.<resourcetype>.<resourcename>

For example:

Copy Code code as follows:
Setcontentview (Resource.Layout.Main); EditText Phonenumbertext = findviewbyid<edittext> (Resource.Id.PhoneNumberText);

(2) Way 2--referencing resources in an XML (or axml) layout file

Format:@[<packagename>:]<resourcetype>/<resourcename>

For example (see Main.axml file):

Copy Code code 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 " > <imageview android:id= "@+id/myimage" android:layout_width= wrap_content "android:layout_height=" Wrap_ Content "android:src=" @drawable/flag "/></linearlayout>

5. Other Alternate resource folders

The standby resource is also saved under the Resources folder, and the subfolder is in the following format:

<ResourceType>-<Qualifier>

That is,:< resource type >-< qualified identifier >

For example: drawable-hdpi

When there are multiple qualifiers, each qualifier is separated by a dash.

Qualifiers must appear in the order listed in the following table (the table is actually arranged by priority from highest to lowest):

For example, the target of V11 is the API level (Android 3.0) device.

Below is the meaning of each qualifier in the screenshot table.

MCC, MNC

mobile phone's country code (MCC): SIM card provider for mobile phones.

Mobile Network Code (MNC): the network provider to which the mobile phone is connected.

Although localization targets can use the country code for mobile devices, it is recommended that you qualify it with a resource qualifier. For example, the resource qualifier for the United States (U.S) is mcc310-mnc026

The complete code for MCC is detailed in the following website: http://mcclist.com/

Language

Two-letter ISO 639-1 national language code and optional two-letter Iso-3166-alpha-2 area code. If both qualifiers are provided, separate them with "-R".

For example: For French-Canadian locales, the resource qualifier used is: Fr-rca

Complete language and area coding see "Codes for the" representation of Names of Languages and Country Names and code elements.

Smallest Width

Limits the minimum width used for screen execution. For example: SW320DP indicates that the target device has a height and width minimum of 320DP.

Available Width, Available Height

Available Width: Screen minimum width, format: W<N>DP, where N represents a pixel-independent width. This value is changed when the user rotates the screen. For example: W720DP indicates the minimum width of the target device is 720DP

Available Height: Screen minimum height, format: H<N>DP, where N represents a pixel-independent width. This value is changed when the user rotates the screen. For example: H720DP indicates that the target device has a minimum height of 720DP

Screen aspect

Refers to the aspect ratio of the screen, rather than the order in which the screen is placed (portrait and landscape). There are two values: long (for wide screens), Notlong (for a non-wide screen).

Screen orientation

Screen placement order, Portrait (portrait placement) or Landscape (landscape placement). This value can be changed during the life cycle of the application. Values are: port, land

Dock mode

The device is in the car dock or the desk dock. API 8 (Android 2.2.x) has been provided. Values are: car, desk

Night mode

Whether the application is running in night mode. This qualification allows developers to provide optimization options during the application lifecycle. API Level 8 (Android 2.2.x) has been provided.

Possible values: Night, Notnight

Screen pixel density (dpi)

The number of pixels of the physical screen, usually expressed in DPI. The possible values are:

ldpi– Low resolution screen

mdpi– Medium Resolution Screen

hdpi– High resolution Screen

xhdpi– Super High resolution screen

nodpi– resources are not scalable

tvdpi– between MDPI and hdpi.

Touchscreen type

Define what kind of touch screen the device is. Possible values are: Notouch (touch-free), stylus (resistive touch screen for stylus), finger (finger touch)

Keyboard availability

Qualify which keyboard is available. It can be changed during the life cycle of the application. The possible values are:

keysexposed– the device has a keyboard available. If the soft keyboard is not available, use only the hard keyboard when the hardware keyboard setting is turned on.

The keyshidden– device does not have a hard keyboard, and the soft keyboard is also hidden. That is, the software has no keyboard to use.

The keyssoft– device has a soft keyboard available.

Primary Text Input Method

Define which hardware keyboard is available for input. The possible values are:

nokeys– No Available hardware keyboard for entering text information.

Qwerty– has a QWERTY keyboard available.

12key– has a 12-key (12-key) hardware keyboard available.

Navigation key Availability

Used when the "5-way" or "D-pad (directional-pad)" Navigation keys are available. Can be changed during the application lifecycle. The possible values are:

navexposed– users can use the navigation keys.

The navhidden– navigation key is not available.

Primary Non-touch Navigation method

The available navigation keys provided by the device. The possible values are:

Nonav– can only navigate by touching the screen.

dpad– has available "D-pad (directional-pad)" Navigation.

The trackball– device has a "trackball" for navigation.

Wheel-(uncommon) has one or more available directional wheels

Platform version (API level)

API level for device support (supported). Format:v<n>

The following figure lists the rules of the Android decision:

Iv. annexes (various documents under the assets folder)

In Android apps, the asset folder and its subfolders can hold any type of original file: text, XML, fonts, music, video 、...... , and so on (WPF's content file type, in other words, if you know how to read and write a content file in a WPF project with C #, you know how to read and write to the original file in the Asset folder in the Android project).

Unlike resource files, files under the Asset folder are not compiled into an Android application, but are packaged in a separate raw (raw) file as an attachment along with the Android app in a. APK compressed package.

Compared to WPF: In WPF, this file is referred to as a content file, and WPF specifies how the compiler handles such files (copied to the output directory: always replicated, if newer, replicated, and so on) by file properties. However, WPF does not require that this type of file be saved to which folder in the project and its subfolders. Android requires that this type of file be saved to the asset folder in the project and its subfolders, and that only the files under that folder can be opened through the assets class.

The following code shows how to read a text file under assets and display it to an interface:

Using Android.app;
Using Android.os;
Using Android.widget;
Using System.IO;
Namespace Mytestproj
{
  [activity (Label = ' Activity1 ')] ' public
  class activity1:activity
  {
    protected override void OnCreate (Bundle savedinstancestate)
    {
      base. OnCreate (savedinstancestate);
      Base. OnCreate (savedinstancestate);
      var textView1 = new TextView (this);
      string content;
      using (StreamReader sr = new StreamReader (Assets.open ("readme.txt"))
      {
        content = Sr. ReadToEnd ();
      }
      Textview1.text = content;
      Setcontentview (TextView1);}}


In an Android application, each component is a separate module, but not all components are the real portal for users to access the program, some of which depend on other components.

Android has four different application components built into it: activity, Service, Content provider, and broadcast recevicer. In addition, you can customize the component and save it to the project's Components folder.

In later chapters, you'll also be able to focus on these, and you just need to remember that you really have the Android application development technology and you have to understand what these components mean and where they are used.

VI. Authority setting and management (Androidmanifest.xml)

A manifest (Manifest) defines the structure and metadata of an application and its components.

The Androidmanifest.xml file is included in each Android application, which describes the components included in this program, the functions implemented, the data that can be processed, the resources to request, and so on.

The function of this file is similar to the Web.conig file in the Web site.

When you add or remove permissions in a Androidmanifest.xml file, the most common use is to set permissions (Permissions)-related properties by VS2015 the item properties under the main menu:

You can also double-click the project's Properties folder in Solution Explorer to go directly to the interface.

When set, it automatically updates the Androidmanifest.xml file under the Properties folder in the project. If the file does not exist under the Properties folder for the project, it is created automatically.

Before the Android system can start a program component, the system must read the program's Androidmanifest.xml file to see if the component exists. So for the Java developer, the program must declare all of its components in this file.

In addition to declaring program components, this profile does some other work, such as:

Determine which user rights The program needs, such as network access or read the user's contacts. Declares the minimum API level required by the program to refer to what APIs are used by the program. Declares the hardware and software features that the program uses or requires, such as cameras, Bluetooth services, or multi-touch screens. The program requires a linked API class library (class libraries other than the Android framework API), such as the Google map class library.

However, if you are developing in C #, "declaring directly in a androidmanifest.xml file" is not required, because declaring it with an attribute declaration with a smart hint, and then having the compiler automatically generate the appropriate code to add to this file is more convenient.

Of course, you can do this if you want to add a statement directly to the file. In other words, C # development gives you a variety of ways to declare a list, and you just have to choose the right way in your own habits. These methods are:

Add the declaration directly in the Androidmanifest.xml file. Select from the project's Properties window and have the compiler automatically add the appropriate code to the Androidmanifest.xml file. Declare in the AssemblyInfo.cs file, and then let the compiler automatically add the appropriate code to the Androidmanifest.xml file. Declare it by adding an attribute declaration above the class, and then let the compiler automatically add the appropriate code to the Androidmanifest.xml file.

In these ways, you have the greatest flexibility, and the code looks simple and intuitive.

VII. CPU Architecture (CPU architectures)

VS2015 debug Mode (Debug) uses a pattern that adapts to a variety of CPU architectures, release modes (releases) are used to select a specific type of phone, and then deploy.

(1) How to specify the Supported CPU architecture

Under Debug State (Debug), the following two options are selected by default:

The two options are selected. Prevents you from specifying a specific CPU schema (CPU architectures) when debugging, in which the following options are not changed:

In general, you need to explicitly configure the CPU architecture or architecture used when you actually publish your application. When changed to release mode, it automatically does not check the "use Shared Runtime" and "Use Fast delployment ..." checkbox, so the options in the above illustration are optional.

Xamarin.android provides the following schema:

Armeabi– is based on ARM's CPU series, providing instruction sets that are not less than the ARMV5TE structure. Note that Armeabi is not thread-safe and cannot be used for multiple-CPU devices. armeabi-v7a– This CPU supports hardware floating-point operations and multiple CPU (SMP) devices. Note that the ARMEABI-V7A machine code cannot be run on the ARMV5 device. arm64-v8a– This is a CPU based on the 64-bit ARMV8 architecture. x86– This CPU provides a x86 (or IA-32) instruction set. This instruction set is equivalent to Pentium Pro (Pentium Pro), including MMX, SSE, SSE2, and SSE3 instruction sets. x86_64 CPUs provides a 64-bit set of x86 instructions.

In release mode, xamarin.android specifies the armeabi-v7a by default, and its performance is higher than that of Armeabi. If the release target is the 64-bit arm platform (for example, Nexus 9), then you need to select ARM64-V8A. If you publish to a x86 device, select x86, and if the release target is 64-bit CPU architecture, select x86_64.

Note: Since 32-bit programs can be run on 64-bit architectures (for example, Nexs 9 is 64-bit arm devices), it is not necessary to select arm64-v8a or x86_64 when publishing to a 64-bit device, and you can still select 32-bit architectures. The advantage of this is that you can avoid an application consuming too much memory.

(2) Multi-platform target (targeting multiple platforms)

The advantage of multiple platforms is that multiple CPUs can be debugged at the same time, with the disadvantage that it causes the. apk file to be large and, if you want to reduce the size of the. apk file, select only one platform when publishing.

Note: Although 64-bit functionality can be experienced in xamarin.android 5.1.x or later, it is not used when it is actually published.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.