Basic Android tutorial -- 10.8 LayoutInflater (layout Service)

Source: Internet
Author: User

Basic Android tutorial -- 10.8 LayoutInflater (layout Service)
Basic Android tutorial -- 10.8 LayoutInflater (layout Service)

Tags (separated by spaces): basic Android tutorial

This section introduces:

This section continues with LayoutInflater (layout Service) in the Android system service.
It may be remembered that after writing a layout xml, call Activity's setContentView () to load the layout, and then display it
On the screen, right ~ In fact, the underlying layer is still the LayoutInflater, Which is parsed using the Android built-in Pull parser.
Layout. It is generally used to dynamically load the layout of Android or add controls. In this section, we will learn about the actual development process.
Some Usage ~
Official API documentation: LayoutInflater

1. LayoutInflater Introduction 1) What is Layout?

A: a system service used to load the Layout is to instantiate the View object corresponding to the Layout XML file and cannot be used directly,
Need to passGetLayoutInflater() Method orGetSystemService() Method to obtain
LayoutInflater instance!

2) LayoutInflater usage

① Three methods for obtaining the LayoutInflater instance:

LayoutInflater inflater1 = LayoutInflater.from(this);  LayoutInflater inflater2 = getLayoutInflater();  LayoutInflater inflater3 = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  

PS: the next two actually follow the first method at the underlying layer ~

② Method of loading layout:

Public ViewInflate(Int resource, ViewGroup root, boolean attachToRoot)
The three parameters of this method are:
① Resource id corresponding to the layout to be loaded
② Nest a parent layout for the exterior of the layout. If you don't need it, write null!
③ Whether the root layout is set for the outermost layer of the loaded layout file. If this parameter is not set,
If root is not null, the default value is true.
If root is null, attachToRoot does not work!
If root is not null and attachToRoot is true, a root layout is nested at the outermost layer of the loaded layout file;
If this parameter is set to false, the root account will be ineffective!
A simple understanding is:Whether to add a root outer container for the loaded layout ~!

③ Use LayoutInflater. LayoutParams to set relevant attributes:

For example, RelativeLayout can also use the addRule method to add rules, that is, to set the location: Is it referring to the parent container?
Or refer to the Child control? Or set margin, etc. This is up to you ~

2. loading layout of pure Java code

We are used to generating the layout we need using XML, but in some specific situations
You need to use Java code to dynamically add components or layout to our layout!
However, we do not recommend that you use Java code to compile the Android page layout. The first point is that there will be more code,
We recommend that you use xml to complete the layout, and then use
Java code modifies the components in it. Of course, you may need to use Java to dynamically add components!

Java-only code loading layout process:

-- Step 1:

Create a container: LinearLayout ly = new LinearLayout (this );
Create component: Button btnOne = new Button (this );

-- Step 2:

You can set related attributes for containers or components:
For example:LinearLayout, We can set the component arrangement direction:Ly. setOrientation (LinearLayout. VERTICAL );
The component can also: such as Button:BtnOne. setText ("button 1 ");
For details about how to set attributes, see the Android API. Generally, you only need to add the property set in xml. For example
SetPadding(Left, top, right, bottom );

-- Step 3:

Add a component or container to the container. In this case, you may need to set the position for adding the component or set its size:
We need to use a class: LayoutParams. we can regard it as an information package for layout containers! Encapsulation location and size
And other information! First demonstrate how to set the size: (the preceding LinearLayout can be changed based on different containers)

LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(          LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

It's easy. Now we can set the location. If we set the location, we usually only consider RelativeLayout!
The addRule () method of LayoutParams is used in this case! You can add multiple addRule!
Set the position of the component in the parent container,

For exampleSet the method of the component:

RelativeLayout rly = new RelativeLayout(this);  RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(                  LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  lp2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);  Button btnOne = new Button(this);  rly.addView(btnOne, lp2);  

Refer to other components for their methods:
(The disadvantage is that you need to manually set an id for the reference component.Manual!!!!)
For example, after btnOne is set to center, BtnTwo is placed below btnOne and on the right of the parent container!

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); RelativeLayout rly = new RelativeLayout (this); Button btnOne = new Button (this); btnOne. setText (Button 1); Button btnTwo = new Button (this); btnTwo. setText (Button 2); // set an id value btnOne for button 1. setId (123); // set the position of Button 1, center in the parent container RelativeLayout. layoutParams rlp1 = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); rlp1.addRule (RelativeLayout. CENTER_IN_PARENT); // you can specify the position of Button 2 at the bottom of Button 1 and align it with RelativeLayout on the right of the parent container. layoutParams rlp2 = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); rlp2.addRule (RelativeLayout. BELOW, 123); rlp2.addRule (RelativeLayout. ALIGN_PARENT_RIGHT); // Add the component to the external container rly. addView (btnTwo, rlp2); rly. addView (btnOne, rlp1); // set the View loaded by the current View to rly setContentView (rly );}}

-- Step 4:

Call setContentView () to load the layout object!
In addition, if you want to remove the View from a container, you can call the container.RemoveView(Component to be removed );

Run:

3. dynamically add controls or xml la s to Java code

Second, we will explain how to use pure Java code to load the layout. In practice, there is not much to use, but more often it is dynamic.
Add View Control and dynamic loading XML layout!

1) dynamically add View in Java code

There are two ways to add components dynamically, the difference is whether you need to firstSetContentView (R. layout. activity_main);
The following example shows how to add a Button in two different ways:

Write a layout file first:Activity_main.xml:


        
     
   
    

First, you do not need to setContentView () to load the layout file first:

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); Button btnOne = new Button (this); btnOne. setText (I am a dynamically added button); RelativeLayout. layoutParams lp2 = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); lp2.addRule (RelativeLayout. CENTER_IN_PARENT); LayoutInflater inflater = LayoutInflater. from (this); RelativeLayout rly = (RelativeLayout) inflater. inflate (R. layout. activity_main, null ). findViewById (R. id. relativeLayout1); rly. addView (btnOne, lp2); setContentView (rly );}}

The second method does not require setContentView () to load the layout file first:

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Button btnOne = new Button (this); btnOne. setText (I am a dynamically added button); RelativeLayout. layoutParams lp2 = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); lp2.addRule (RelativeLayout. CENTER_IN_PARENT); RelativeLayout rly = (RelativeLayout) findViewById (R. id. relativeLayout1); rly. addView (btnOne, lp2 );}}

Analysis Summary:

The code is very simple. After the Button is created, we create a LayoutParams object to set the Button size,
The location of the Button is also set through the addRule () method!
Method 1: The activity_main layout is loaded using the inflate () method of LayoutInflate, and the outer container is obtained,
Add the addView button to the container and setContentView ();
Method 2: Because we have loaded the layout through the setContetView () method, now we can use
FindViewById: Find the outer container, addView, and setContentView!
In addition, the view node set by setContentView () is the root node of the entire XML file!

2) Java code dynamically loads xml Layout

Next, let's change one. The xml file is loaded this time!Dynamically add xml files!
First, write down the main layout file and the Dynamically Loaded layout file:

Activity_main.xml:


      
    

Inflate. xml:

   
        
         
   
     

Next to ourMainActivity. javaThe xml layout is dynamically loaded here:

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the LayoutInflater object; final LayoutInflater inflater = LayoutInflater. from (this); // obtain the external container object final RelativeLayout rly = (RelativeLayout) findViewById (R. id. relativeLayout1); Button btnLoad = (Button) findViewById (R. id. btnLoad); btnLoad. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {// load the layout object LinearLayout ly = (LinearLayout) inflater. inflate (R. layout. inflate_ly, null, false ). findViewById (R. id. ly_inflate); // sets the size and position of the loaded layout. layoutParams lp = new RelativeLayout. layoutParams (LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT); lp. addRule (RelativeLayout. CENTER_IN_PARENT); rly. addView (ly, lp );}});}}

Run:

Code Analysis:

① Get the container object:
Final RelativeLayout rly = (RelativeLayout) findViewById (R. id. RelativeLayout1 );
② Obtain the Inflater object, load the xml of the added layout, and find the root node of the outermost layer through findViewById
Final LayoutInflater inflater = LayoutInflater. from (this );
LinearLayout ly = (LinearLayout) inflater. inflate (R. layout. inflate_ly, null, false)
. FindViewById (R. id. ly_inflate );
③ Set the size and location information for the container:
RelativeLayout. LayoutParams lp = new RelativeLayout. LayoutParams (
LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT );
Lp. addRule (RelativeLayout. CENTER_IN_PARENT );
④ Add to outer container:
Rly. addView (ly, lp );

4. LayoutInflater's inflate () method source code

Finally, let's provide the source code of LayoutInflater's inflate () method. If you are interested, please refer ~, Actually, it's just Pull parsing ~

public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {        synchronized (mConstructorArgs) {            final AttributeSet attrs = Xml.asAttributeSet(parser);            mConstructorArgs[0] = mContext;            View result = root;            try {                int type;                while ((type = parser.next()) != XmlPullParser.START_TAG &&                        type != XmlPullParser.END_DOCUMENT) {                }                if (type != XmlPullParser.START_TAG) {                    throw new InflateException(parser.getPositionDescription()                            + : No start tag found!);                }                final String name = parser.getName();                if (TAG_MERGE.equals(name)) {                    if (root == null || !attachToRoot) {                        throw new InflateException(merge can be used only with a valid                                 + ViewGroup root and attachToRoot=true);                    }                    rInflate(parser, root, attrs);                } else {                    View temp = createViewFromTag(name, attrs);                    ViewGroup.LayoutParams params = null;                    if (root != null) {                        params = root.generateLayoutParams(attrs);                        if (!attachToRoot) {                            temp.setLayoutParams(params);                        }                    }                    rInflate(parser, temp, attrs);                    if (root != null && attachToRoot) {                        root.addView(temp, params);                    }                    if (root == null || !attachToRoot) {                        result = temp;                    }                }            } catch (XmlPullParserException e) {                InflateException ex = new InflateException(e.getMessage());                ex.initCause(e);                throw ex;            } catch (IOException e) {                InflateException ex = new InflateException(                        parser.getPositionDescription()                        + :  + e.getMessage());                ex.initCause(e);                throw ex;            }            return result;        }    }    
 

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.