"Go" Android Development Tour: In-depth analysis of layout files & Again "Hello world! ”

Source: Internet
Author: User
Tags unique id xml parser

Introduction

The last article can be said to be a watershed, it marks us from the Android application theory into practice, we picked up the scalpel to the default "Hello world! "The program carried out 3 surgeries, and we were clear," Hello world! "Is how it is implemented on the screen, and we know that not only can the screen be initialized according to the layout file Main.xml, but also programmatically. In the future we will be in a practical way to penetrate the development of Android. This time we delve into the layout files of Android applications, the main content is as follows:

    • 1. User interface and view level
    • 2. How to define the layout in Android
    • 3. Writing XML layout files and loading XML resources
    • 4. Attributes of elements in common layout files
      • 4.1. ID attribute
      • 4.2. Layout parameters
    • 5. Layout position & size & offset & margin
    • 6, again "Hello world! ”
      • 6.1, again "Hello world! "(i)
      • 6.2, again "Hello world! "(ii)
      • 6.3, again "Hello world! "(iii)

1. User interface and view level

In through the "Hello world! "Before you introduce the layout problem in Android, you have to introduce the user interface in Android because layout issues are also one of the user interface issues. In an Android application, the user interface is built from the View and viewgroup objects. There are many kinds of views and viewgroups in Android, and they all inherit from the View class. The View object is the basic unit on the Android platform that represents the user interface.

View class:

extends  object
implements   drawable.callback      Keyevent.callback accessibilityeventsource

This class represents the basic building block of a user interface component, a view that occupies a rectangular area on the screen, and is responsible for drawing and event processing. The View class is the base class for widgets , andwidgets is used to create interactive UI components (buttons, text fields, and so on). The direct subclass of the View class ViewGroup class is the base class for layouts ,layouts It is invisible to the container user to keep other views or other viewgroups and define their layout properties.

A View object is a data structure whose properties store the layout parameters and contents of a particular rectangular area on the screen. A View object handles its own measurement, layout, drawing, focus change, scrolling, key/gesture interaction with the rectangular area on the screen. As an object in the user interface, view is also a point of interaction with the user and an interactive event receiver.

On the Android platform, you define the active UI using the view and ViewGroup nodes as shown in the hierarchy. Depending on your needs this hierarchy tree can be simple or complex, and you can use the Android pre-defined widgets and layouts collections, or use custom views.

Figure 1, view hierarchy

In order to render the view hierarchy tree to the screen, your activity must call the Setcontentview () method and pass a reference to the root node object. The Android system receives this reference and uses it to validate, measure, and draw the tree. The root node of the hierarchy requires its child nodes to draw its own--each attempt to group nodes accordingly requires the call of their own child view to draw themselves. The child view may request the specified size and position in the parent view, but the parent view object has the final decision (where and how large the child view is). Because they are drawn sequentially, if the elements overlap, the overlapping portions are drawn on top of the previously drawn ones.

2. How to define the layout in Android

A layout is a schema for the user interface in an activity that defines the layout structure and stores all the elements that are displayed to the user. There are two ways to declare the layout, which we have already used (corresponding to the "Hello World Surgery (ii)", "Hello World Surgery (iii)" above). Let's revisit the summary:

    • method One, declares the UI in an XML-formatted layout file. Android provides a simple XML glossary corresponding to the view class and its subclasses such as widgets and layouts.

    • method Two, instantiate the layout element at run time . You can programmatically create view and ViewGroup objects and manipulate their properties.

The Android framework gives us the flexibility to use one or two of these two methods to declare and manage your application's UI. For example, you can define an application's default layout in an XML-formatted layout file, including the elements and attributes that will be displayed on the screen. You can then programmatically modify the state of the objects on the screen, including the elements defined in the XML file.

One of the most commonly used methods is to define your own layout and expression hierarchy view with an XML layout file. XML provides an intuitive layout structure, similar to HTML. Each element in the XML is a view or ViewGroup object (or inherited from their object). The View object is a leaf in the tree, and the ViewGroup object is a branch in the tree, as you can see from the View hierarchy tree above.

The advantage of declaring the UI in an XML layout file is that the interface of the application is better decoupled from the code that controls its behavior . The UI is described in addition to the application code, which means that you can modify or tweak it without modifying your source and recompiling it. For example, you can create an XML layout file for different screen orientations, different screen sizes, and different languages. In addition, declaring layouts in XML is easier to visualize your UI structure, making it easier to debug problems.

The name of an element XML element corresponds to a Java class, so a <TextView> element creates a TextView in your UI, a <linearLayout> element to create a LinearLayout view group. When you load a layout resource, the Android system initializes these runtime objects, corresponding to the elements in your layout. The attributes of an XML element correspond to a method of a Java class.

3. Writing XML layout files and loading XML resources

Using the Android XML vocabulary, we can quickly design the UI layout and the contained screen elements, just like the HTML of a Web page. Each layout file must contain a root element, and the root element must be a view or ViewGroup object. Once you have defined the root element, you can add additional layout objects or widgets as child elements, and gradually build a view hierarchy to define your layout. For example, the following XML layout file uses the portrait linearlayout to save a textview and a button.

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:orientation= "Vertical" >
<textview android:id= "@+id/text"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= "Hello, I am a TextView"/>
<button android:id= "@+id/button"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= "Hello, I am a button"/>
</LinearLayout>

The layout file is extended with. XML and is saved under res/layout/ , and it will be compiled correctly. We've already defined the layout file, so how did it get loaded? When we compile the application, each XML layout file is compiled into a view resource. We should load the layout resource in the application code and implement it in the activity.oncreate () callback by calling Setcontentview () to R.layout.layout_ The file_name form is passed to the reference of its layout resource. For example, if your XML layout is saved as Main_layout.xml, you should load it like this:
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview. (R.layout.main_layout);
}
The onCreate () callback method in the activity is called by the Android framework when your activity starts (see Android Development Tour: Component Lifecycle (i), detailing the life cycle of the active component).

4. Attributes of elements in common layout files

Each view and ViewGroup object supports their own various XML attributes. Some properties are specific to a view object (for example, TextView supports TEXTSIZE properties), but these properties are also inherited by any view object that inherits from the class. Some properties are available for all view objects because they inherit from the root view class (such as the id attribute). Also, other properties are considered "layout parameters", which describe the specific layout direction of a particular view object, defined by the object's parent ViewGroup object.

4.1. id attribute

Each view object has an associated ID that uniquely identifies it. This ID is referenced as an integer when the application is compiled. However, the ID is usually assigned as a string in the layout XML file as the id attribute of the element. This XML property is available for all view objects and is often used. The ID syntax in XML is as follows:

Android:id= "@+id/my_button"

The @ symbol before the string indicates that the XML parser should parse and extend the remaining ID string and use it as an ID resource. The + symbol indicates that this is a new resource name, it must be created and added to our resources (R.java file, R is Resource). The Android Framework provides some additional ID resources. When referencing an Android resource ID, you do not need the + symbol, but you must add the Android package namespace as follows:

Android:id= "@android: Id/empty"

In order to create views and reference them from the application, the usual pattern is:

    1. First, define a view/artifact object in the layout file and assign a unique ID:
      <button android:id= "@+id/my_button"
      Android:layout_width= "Wrap_content"
      android:layout_height= "Wrap_content"
      android:text= "@string/my_button_text"/>
    2. Then create an instance of the View object and get it from the layout (typically in the onCreate () method):
      Button MyButton = (button) Findviewbyid (R.id.my_button);
4.2. Layout Parameters

An XML layout property named layout_something that defines the layout parameters that are appropriate for the viewgroup that it resides on. Each ViewGroup class implements a nested class that extends from viewgroup.layoutparams . This subclass contains the attribute types that define the size and location for each child view, to fit in the view group. As shown, the parent view group defines layout parameters, including child view groups, for each child view.


Figure 2, Layout parameters

Note that each layoutparams subclass has its own syntax for setting values. Each child element must define a layoutparams that is appropriate for its parent view, although it may also define different layoutparams for its own child views.

All view groups include broadband and height (layout_width and layout_height), and each view requires that you define them. Many layoutparams also include optional margins and boundaries. You can specify a specific value for width and height, although you may not want to do so. More you will tell the view that its size depends on its content requirements or as large as the parent view group allows (with wrap_content and fill_parent values, respectively).

5. Layout position & size & offset & margin

The geometric shape of the view is a rectangle. The position of the view is represented as a pair of left and top coordinates, and the dimensions (dimensions) are expressed as widths and heights. The position and dimensions are in pixels (pixel).

You can retrieve the location of the view by calling GetLeft () and GetTop () . The former returns the left or X of the view rectangle coordinates, which returns the right or y of the view rectangle coordinates. These methods return relative to their parent view, such as when getLeft () returns 20, that is, the left distance of the view to its immediate parent view is 20 pixels.

In addition, some additional methods such as getRight () and Getbuttom () are provided to avoid unnecessary computations. These methods return the right and bottom margins of the view coordinates. For example, calling GetRight () is equivalent to the following calculation:getLeft ()+getwidth ().

The size of the view is also expressed as width and height, but is different from the above dimensions (dimensions). The dimensions above define how large the view wants to be in the parent view, and the dimensions of the view can be obtained by Getmeasurewidth () and getmeasureheight () . The size of the view represents the actual size of the view on the screen, and their values can be different from the view size, but this is not necessarily the case. The size of the view can be obtained by GetWidth () and getheight () .

To measure the dimensions of a view, you must consider its padding (padding, the distance between the view content and the view border). The padding in pixels represents the white space of the left, top, right, and bottom portions of the view. The padding can be used to offset the view content by a specific number of pixels. For example, the left padding is 2 the output content is 2 pixels from the left border. The padding can be set through the setpadding (int, int , int, int) method and through getpaddingleft (),getpaddingright (), Getpaddingtop (),Getpaddingbottom () to query. Although a view can define padding, it does not support margins (margins). However, the view group supports margins.

6, again "Hello world! "

Below we pass several experiments to verify and deepen the above about the layout file understanding.

6.1, again "Hello world! "(i)

Validates the XML layout properties named layout_something , defining the width and height of the button with layout_width and layout_height . Both of these properties are also defined by each view object that must be declared. Verify the difference between Wrap_content and fill_parent, in fact, the difference from their word composition can be seen: wrap--package, parcel and so on content--content, then wrap_content that the height/width of the View object is wrapped content; fill-- Fill, and so on parent--the parent, the fill_parent represents filling up the parent view.

Experiment is set to: Define two Button,id in the layout resource file for button1, Button2,button1 width and Height properties are all wrap_content,button2 width and Height properties are fill_parent. The Main.xml file code is as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:orientation= "Vertical" >
<button android:id= "@+id/button1"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= "Hello, I am a button"/>
<button android:id= "@+id/button2"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:text= "Hello, I am a button"
/>
</LinearLayout>
and the Helloworld.java file code is:
Package skynet.com.cnblogs.www;

Import android.app.Activity;
Import Android.os.Bundle;
Import android.widget.*;//Note: This package is imported, or Android.widget.Button;

public class HelloWorld extends Activity {
Private Charsequence text= "New hello!";


@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
}
}
The run can be obtained as a result:

Figure 3, validating XML layout properties named layout_something

It is obvious that the size of the button1 is exactly the same as the content "hello,i am a button", while the size of button2 fills the size of the parent view.

6.2, again "Hello world! "(ii)

Next we have a common property ID for the View object and two ways to validate the layout again. (About ID Properties--First define a View/artifact object in the layout file and assign a unique ID, then create an instance of the View object and get it from the layout (typically in the onCreate () method).)

The properties experiment is set to: basically the same as above, but we want to programmatically modify the Text property of the button1. Main.xml layout file is the same as above, and the main is the Helloworld.java file is not the same, its code is as follows:
Package skynet.com.cnblogs.www;

Import android.app.Activity;
Import Android.os.Bundle;
Import android.widget.*;
Import Android.widget.Button;

public class HelloWorld extends Activity {
Private Charsequence text= "New hello!";


@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
button mybutton= (button) Findviewbyid (R.id.button2);
Mybutton.settext (text);

}
}
The two lines of red bold above are programmed to change the text property of Button2, which shows that the Android framework gives us the flexibility to use one or two of the above two methods to declare and manage your application's UI. The results of the operation are as follows:

Figure 4, common patterns for validating the common property ID of a View object and programmatically changing the properties of a button defined in an XML layout file

6.3, again "Hello world! "(iii)
Verify the layout position & size & padding of the View object, and experiment is set to: Modify the Button1 layout position, size, and padding properties in main.xml on the basis of experiment one. The modified Mian.xml file is as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
android:orientation= "Vertical" >
<button android:id= "@+id/button1"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= "Hello, I am a button"
android:width= "250DP"
android:height= "80DP"
Android:padding= "20DP"
Android:layout_margin= "20DP"

/>
<button android:id= "@+id/button2"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
Android:text= "Hello, I am a button"
/>
</LinearLayout>
After the run, the results are as follows:

Figure 5, verifying the layout position & size & padding of the View object

Note: units of layout position & size & padding in the above code (e.g. width= "250DP"). Units can be PX, in, MM, PT, DP, SP.

      • Px:pixels (pixels)--corresponds to the actual pixel on the screen
      • In:inches (Inch)--based on the size of the physical screen
      • Mm:millimeters (mm)--based on the size of the physical screen
      • Pt:points (dots)--inches of 1/72, based on the size of the physical screen
      • Dp:density-independent Pixels (pixel independent of density)-an abstract unit based on the density of the physical screen. These units are relative to a 160dpi screen, and all one DP is a point on the 160dpi screen. The conversion ratio of DP to PX varies by screen density, but is not necessarily proportional.
      • Sp:scale-independent pixels (scale independent pixels)-Similar to DP units, but it is also affected by user font size settings. Use it when you specify the font size, as they will adjust according to the screen and user settings.

"Go" Android Development Tour: In-depth analysis of layout files & Again "Hello world! ”

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.