Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

LinearLayout

The LinearLayout is the most basic layout, and it arranges its elements sequentially, either horizontally or vertically. To arrange controls within a linear layout, the following attributes are used:

  • android:orientation—Used for arranging the controls in the container in horizontal or vertical order
  • android:layout_width—Used for defining the width of a control
  • android:layout_height—Used for defining the height of a control
  • android:padding—Used for increasing the whitespace between the boundaries of the control and its actual content
  • android:layout_weight—Used for shrinking or expanding the size of the control to consume the extra space relative to the other controls in the container
  • android:gravity—Used for aligning content within a control
  • android:layout_gravity—Used for aligning the control within the container

Applying the orientation Attribute

The orientation attribute is used to arrange its children either in horizontal or vertical order. The valid values for this attribute are horizontal and vertical. If the value of the android:orientation attribute is set to vertical, the children in the linear layout are arranged in a column layout, one below the other. Similarly, if the value of the android:orientation attribute is set to horizontal, the controls in the linear layout are arranged in a row format, side by side. The orientation can be modified at runtime through the setOrientation() method. That is, by supplying the values HORIZONTAL or VERTICAL to the setOrientation() method, we can arrange the children of the LinearLayout in row or column format, respectively.

Applying the height and width Attributes

The default height and width of a control are decided on the basis of the text or content that is displayed through it. To specify a certain height and width to the control, we use the android:layout_width and android:layout_height attributes. We can specify the values for the height and width attributes in the following three ways:

  • By supplying specific dimension values for the control in terms of px (pixels), dip/dp (device independent pixels), sp (scaled pixels), pts (points), in (inches), and mm (millimeters). For example, the android:layout_width="20px" attribute sets the width of the control to 20 pixels.
  • By providing the value as wrap_content. When assigned to the control’s height or width, this attribute resizes the control to expand to fit its contents. For example, when this value is applied to the width of the TextView, it expands so that its complete text is visible.
  • By providing the value as match_parent. When assigned to the control’s height or width, this attribute forces the size of the control to expand to fill up all the available space of the enclosing container.

Applying the padding Attribute

The padding attribute is used to increase the whitespace between the boundaries of the control and its actual content. Through the android:padding attribute, we can set the same amount of padding or spacing on all four sides of the control. Similarly, by using the android:paddingLeft, android:paddingRight, android:paddingTop, and android:paddingBottom attributes, we can specify the individual spacing on the left, right, top, and bottom of the control, respectively.

The following example sets the spacing on all four sides of the control to 5 pixels:

android:padding="5dip"

Similarly, the following example sets the spacing on the left side of the control to 5 pixels:

android:paddingLeft="5dip"

Let’s see how the controls are laid out in the LinearLayout layout using an example. Create a new Android Project called LinearLayoutApp. The original default content of the layout file activity_linear_layout_app.xml appears as shown in Listing 3.1.

Listing 3.1. Default Code in the Layout File activity_linear_layout_app.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".LinearLayoutAppActivity" />
</RelativeLayout>

Let’s apply the LinearLayout and add three Button controls to the layout. Modify the activity_linear_layout_app.xml to appear as shown in Listing 3.2.

Listing 3.2. The activity_linear_layout_app.xml File on Adding Three Button Controls

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/Apple"
        android:text="Apple"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Mango"
        android:text="Mango"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Banana"
        android:text="Banana"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

The orientation of LinearLayout is set to vertical, declaring that we want to arrange its child elements vertically, one below the other. The height and width of the layout are set to expand to fill up all the available space of the enclosing container, that is, the device screen. Three Button controls are added to the layout, which appear one below the other. The IDs and text assigned to the three Button controls are Apple, Mango, and Banana, respectively. The height of the three controls is set to wrap_content, which is enough to accommodate the text. Finally, the width of the three controls is set to match_parent, so that the width of the three controls expands to fill up the available space of the LinearLayout container. We see the output shown in Figure 3.1.

Figure 3.1

Figure 3.1. Three Button controls arranged vertically in LinearLayout

To see the controls appear horizontally, set the orientation attribute of the LinearLayout to horizontal. We also need to set the layout_width attribute of the three controls to wrap_content; otherwise, we will be able to see only the first Button control, the one with the Apple ID. If the layout_width attribute of any control is set to match_parent, it takes up all the available space of the container, hiding the rest of the controls behind it. By setting the values of the layout_width attributes to wrap_content, we make sure that the width of the control expands just to fit its content and does not take up all the available space. Let’s modify the activity_linear_layout_app.xml to appear as shown in Listing 3.3.

Listing 3.3. The activity_linear_layout_app.xml File on Setting Horizontal Orientation to the Button Controls

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <Button
        android:id="@+id/Apple"
        android:text="Apple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Mango"
        android:text="Mango"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Banana"
        android:text="Banana"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

The controls are arranged horizontally, as shown in Figure 3.2.

Figure 3.2

Figure 3.2. Three Button controls arranged horizontally in LinearLayout

Applying the weight Attribute

The weight attribute affects the size of the control. That is, we use weight to assign the capability to expand or shrink and consume extra space relative to the other controls in the container. The values of the weight attribute range from 0.0 to 1.0, where 1.0 is the highest value. Let’s suppose a container has two controls and one of them is assigned the weight of 1. In that case, the control assigned the weight of 1 consumes all the empty space in the container, whereas the other control remains at its current size. If we assign a weight of 0.0 to both the controls, nothing happens and the controls maintain their original size. If both the attributes are assigned the same value above 0.0, both the controls consume the extra space equally. Hence, weight lets us apply a size expansion ratio to the controls. To make the middle Button control, Mango, take up all the available space of the container, let’s assign a weight attribute to the three controls. Modify the activity_linear_layout_app.xml file to appear as shown in Listing 3.4.

Listing 3.4. The activity_linear_layout_app.xml File on Applying the weight Attribute to the Button Controls

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/Apple"
        android:text="Apple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.0" />
    <Button
        android:id="@+id/Mango"
        android:text="Mango"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1.0" />
    <Button
        android:id="@+id/Banana"
        android:text="Banana"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0.0" />
</LinearLayout>

By setting the layout_weight attributes of Apple, Mango, and Banana to 0.0, 1.0, and 0.0, respectively, we allow the Mango button control to take up all the available space of the container, as shown in Figure 3.3 (left). If we set the value of layout_weight of the Banana button control to 1.0 and that of Mango back to 0.0, then all the available space of the container is consumed by the Banana button control, as shown in Figure 3.3 (middle). Similarly if we set the layout_weight of all controls to 1.0, the entire container space will be equally consumed by the three controls, as shown in Figure 3.3 (right).

Figure 3.3

Figure 3.3. (left) The weight attribute of the Mango Button control set to 1.0, (middle) the weight attribute of the Banana Button control set to 1.0, and (right) all three Button controls set to the same weight attribute

Similarly if we set the weight of Apple, Mango, and Banana to 0.0, 1.0, and 0.5, respectively, we get the output shown in Figure 3.4.

Figure 3.4

Figure 3.4. The weight attribute of the Apple, Mango, and Banana Button controls set to 0.0, 1.0, and 0.5

We can see that the text of the three controls is center-aligned. To align the content of a control, we use the Gravity attribute.

Applying the Gravity Attribute

The Gravity attribute is for aligning the content within a control. For example, to align the text of a control to the center, we set the value of its android:gravity attribute to center. The valid options for android:gravity include left, center, right, top, bottom, center_horizontal, center_vertical, fill_horizontal, and fill_vertical. The task performed by few of the said options is as follows:

  • center_vertical—Places the object in the vertical center of its container, without changing its size
  • fill_vertical—Grows the vertical size of the object, if needed, so it completely fills its container
  • center_horizontal—Places the object in the horizontal center of its container, without changing its size
  • fill_horizontal—Grows the horizontal size of the object, if needed, so it completely fills its container
  • center—Places the object in the center of its container in both the vertical and horizontal axis, without changing its size

We can make the text of a control appear at the center by using the android:gravity attribute, as shown in this example:

android:gravity="center"

We can also combine two or more values of any attribute using the | operator. The following example centrally aligns the text horizontally and vertically within a control:

android:gravity="center_horizontal|center_vertical"

Figure 3.5 shows the android:gravity attribute set to left and right for the Button controls Mango and Banana.

Figure 3.5

Figure 3.5. The text in the Mango and Banana Button controls aligned to the left and right, respectively, through the android:gravity attribute

Besides the android:gravity attribute, Android provides one more similar attribute, android:layout_gravity. Let’s explore the difference between the two.

Using the android:layout_gravity Attribute

Where android:gravity is a setting used by the View, the android:layout_gravity is used by the container. That is, this attribute is used to align the control within the container. For example, to align the text within a Button control, we use the android:gravity attribute; to align the Button control itself in the LinearLayout (the container), we use the android:layout_gravity attribute. Let’s add the android:layout_gravity attribute to align the Button controls themselves. To see the impact of using the android:layout_gravity attribute to align the Button controls in the LinearLayout, let’s first arrange them vertically. So, let’s modify activity_linear_layout_app.xml to make the Button controls appear vertically, one below the other as shown in Listing 3.5.

Listing 3.5. The activity_linear_layout_app.xml File on Arranging the Button Controls Vertically

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/Apple"
        android:text="Apple"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Mango"
        android:text="Mango"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/Banana"
        android:text="Banana"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

The preceding code arranges the Button controls vertically, as shown in Figure 3.6 (left). To align the Button controls Mango and Banana to the center and to the right of the LinearLayout container, add the following statements to the respective tags in the activity_linear_layout_app.xml layout file:

android:layout_gravity="center"

and

android:layout_gravity="right"
Figure 3.6

Figure 3.6. (left) The three Button controls vertically aligned with the width attribute set to wrap_content, (middle) the Mango and Banana Button controls aligned to the center and right of container, and (right) the width of the three Button controls expanded to take up all the available space

The two Button controls, Mango and Banana, are aligned at the center and to the right in the container, as shown in Figure 3.6 (middle).

At the moment, the layout_width attribute of the three controls is set to wrap_content. The width of the three controls is just enough to accommodate their content. If we now set the value of the android:layout_width attribute for all three controls to match_parent, we find that all three Button controls expand in width to take up all the available space of the container, as shown in Figure 3.6 (right). Now we can apply the android:gravity attribute to align the text within the controls. Let’s add the following three attributes to the Button controls Apple, Mango, and Banana:

android:gravity="left"
android:gravity="center"

and

android:gravity="right"

These lines of code align the content of the three Button controls to the left, to the center, and to the right within the control, as shown in Figure 3.7 (left). Because the three Button controls are arranged vertically in the layout (the orientation of the LinearLayout is set to vertical), the application of the weight attribute makes the controls expand vertically instead of horizontally as we saw earlier. To see the effect, let’s add the following statement to the tags of all three Button controls:

android:layout_weight="0.0"
Figure 3.7

Figure 3.7. (left) The three Button controls with their text aligned to the left, center, and right, (middle) the vertical available space of the container apportioned equally among the three Button controls, and (right) the text of the three Button controls vertically aligned to the center

As expected, there will be no change in the height of any control, as the weight value assigned is 0.0. Setting an equal value above 0.0 for all three controls results in equal division of empty space among them. For example, assigning the android:layout_weight="1.0" to all three controls results in expanding their height, as shown in Figure 3.7 (middle).

In the middle image of Figure 3.7, we see that the text in the Apple and Banana controls is not at the vertical center, so let’s modify their android:gravity value, as shown here:

android:gravity="center_vertical" for the Apple control

android:gravity="center_vertical|right" for the Banana control

The center_vertical value aligns the content vertically to the center of the control, and the right value aligns the content to the right of the control. We can combine the values of the attribute using the | operator. After applying the values as shown in the preceding two code lines, we get the output shown in Figure 3.7 (right).

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020