Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
12 views
Mobile Application
Laying out controls in containers notes
Uploaded by
Gagan Mm
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save mobile application For Later
Download
Save
Save mobile application For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
12 views
Mobile Application
Laying out controls in containers notes
Uploaded by
Gagan Mm
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download now
Download
Save mobile application For Later
Carousel Previous
Carousel Next
Save
Save mobile application For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 37
Search
Fullscreen
CHAPTER 3 Laying Out Controls in Containers A container is a view used to contain other views. Android offers a collection of view classes that act containers for views. These container classes are called and as the name suggests, they decide the organi- and position of their children views. layouts, zation, size) Let's start the chapter with an introduction to'different layouts used in Android applications. Introduction to Layouts Layouts are basically containers for other items known as views, which are displayed on the screen. Layouts help manage and arrange views as well. Layouts are defined in the form of XML files that cannot be changed by our code during runtime. Table 3.1 shows the layout managers provided by the Android SDK, a TABLE 3.1 Android Layout Managers Layout Manager _ Description LinearLayout ~ Organizes its children either horizontally or vertically Organizes its children relative to one another or to the parent Each child control is given a specific location within the bounds of the container RelativeLayout AbsoluteLayout IN THIS CHAPTER > Introduction to Layouts > LinearLayout > Applying the orientation Attribute > Applying Height and width Attributes > Applying the Padding Attribute > Applying the weight attribute > Applying the Gravity Attribute > Using the android: 1ayout_ aravity Attribute > RelativeLayout > Relative Layout Control Attributes > AbsoluteLayout > FrameLayout > TableLayout > TableLayout Operations > GridLayout > Screen Orientation Adaptations “£26299 CMRIT LIBRARY BANGALOR: - 26%102 CHAPTER 3 Laying Out Controls in Containers Layout Manager _ Description FrameLayout Displays a single view: that is, the next view replaces the previous view and hence is used to dynamically change the children in the layout TableLayout Organizes its children in tabular form GridLayout Organizes its children in grid format ki ewGroups as one Or ‘The containers or layouts listed in Table 3.1 are also known as ViewSroups a5 i ‘a desired manner through them. Besides the more views are grouped and arranged in : : viewsroups shown here Android supports one more ViewGroup known as ScrollView, which is discussed in Chapter 4, “Utilizing Resources and Media. LinearLayout The LinearLayout is the most basic layout, horizontally or vertically. To arrange controls within butes are used: > android:orientation—Used for arranging the controls in the container in horizon- and it arranges its elements sequentially, either a linear layout, the following attri- tal or vertical order > android: layout_width—Used for defining the width of a control eight —Used for defining the height of a control > android: layout_! 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: 1ayout_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 verti- cal 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 Horrzontan Or VERTICAL to the setorientation() method, we can arrange the children of the LinearLayout in row or column format, respectively.LinearLayout 103 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 spe: y a certain height and width to the Control, we use the android: Jayout_width and andyoid: layout height attributes. We can spe values for the height and wiaen attributes in the following three way > By supplying specific dimen: ap (device independent pixels fy the jon values for the control in terms of px (pixels), dip/ ), 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 width, this attribute res content. When ass; igned to the control’s height or zes 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 avail- able space of the enclosing container. For layout elements, the value wrap_content resizes the layout to fit the controls added as its children. The value match_paxent makes the layout expand to take up alll the space in the parent layout. 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: paddingbot tom 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 § pix android: paddin Sdip" imilarly, the following example sets the spacing on the left side of the control to 5 pixels: ly 8 P F android:paddingLeft="Sdip" To set the padding at runtime, we can call the set Padaing() method. amoaaie 7 =104 CHAPTER 3 Laying Out Controls in Containers Let’s see how the controls are laid out in the LinearLayout |: Create a new Android Project called LinearLayoutApp. The layout using an example, layout file activ: original default content of thy ity Linea_layout_app.xml appears as shown in Listing 3.1, USTING 3.1 Default Code in the La yout File activity linear_layout_app.xml ‘nttp://schemas andoid.com/apk/res/android" omins:tools="http: //schemas.android.com/tools" android: layout_widt! sRelativeLayout xmlns:andvoi inatch_parent* android: layout_height="match parent" »
Let’s apply the LinearLayout and add three eutton controls to the layout. Modify the activity_linear_layout_app.xm) to appear as shown in Listing 3.2. LISTING ayout_app.xml File on Adding Three Button Controls out xmlns:androi "http: //schemas.android.com/apk/res/android* "match_parent" ‘cid: layout_height="natch_parent" android:orientatione"vertical” >
Button android:id: +id/Mango" android:text="Mango" android: layout_widthe"match parent" android: layout height="wrap_content" /> eputton android: id="s+id/zanana" droid: tex! Banana" android: Jayout_widthe"match_parent" android: layout_height="«rap_content" /> Linearlayout 105 The orientation of LinearLayout is set to vertical, declaring that we want to arrange its child elements vertically, one below the other. h ‘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 lay. . ‘out, which appear one below the other. The IDs and text assigned to the three Burton controls are Appie, Mango, and Banana, respectively. The height of the three controls is set to wrap_content, which is enough to accommodate the text. Finally, on i 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. Eran @ LinearilayoutAppactivity 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 1ayout_width attribute of the three controls to wrap_content; otherwise, we will be able to see only the first sutton control, the one with the appie 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 1ayout_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_1inear_leyout_app.xmi to appear as shown in List- ing 3.3. LUSTING 3.3. The activity_linear_layout_app.xm1 File on Setting Horizontal Orientation to the sutton Controls
106 CHAPTER 3 Laying Out Controls in Containers
‘The controls are arranged horizontally, as shown in Figure 3 2. FIGURE 3.2 Three Button controls arranged horizontally in LinearLayout Applying the weight Attribute ' ae ‘The weaghe attribute affects the size of tne control. That is, we use wes to assign ht capability to expand or shrink and consume extra space relative to the other controls the container. The values of the weight attribute range from 0.0 to 1.0, where 2.018 i highest value. Let's suppose 2 container has two controls and one of them is assigned the mimigne of 2. 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 4 weight of 0.0 to both the controls, nothing happens and the controls maintain their orig vat size. If both the attributes are assigned the same value above 0.0, both the controls vansume the extra space equally, Hence, weight lets us apply a size expansion ratio 10 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_leyout_app.2m] file to appear as shown in Listing 3.4.LinearLayout 407 LISTING 3.4 Tho activity Linear layout app.sm File on Applying the weight Attribute to the natton Controls sbinearbayoul xm nnsandroide"http://echemas android. com/apk/rea/androtd" androldsorlentat ione"hort zontal" android: layout width= "match parent android: layout height <"mateh_parent ls cebu ton android: td="@11a/Apple" android: text ="Apple" android: layout_width="wrap_conteat™ andyoid: layout_height="wap_content™ android: layout_weights"0.0" />
«Button android:id="o+id/Banana* android: text="Banana" android: layout_width=*wrap_content" android: layout_height="#rap_content” android: layout_weight="0.0" /> By setting the layout_weight attributes of apple, mango, and Banana to 0.0, 1.0, and 0.0, respectively, we allow the Hange 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 tango 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 2.0, the entire container space will be equally consumed by the three controls, as shown in Figure 3.3 (right). (yieatae) ‘Apple. {Mongo Bonana FIGURE 3.3 (left) The weight attribute of the Mango gutton control set to 4.0, (middle) the weight attribute of the Banana Button control set to 4.0, and (right) all three Button controls set to the same weight attribute Similarly if we set the weight of apple, Hango, and Banana to 0.0, 1.0, and 0,5, respec- Lively, we get the output shown in Figure 3.4.108 CHAPTER 3 Laying Out Controls in Containers FIGURE 3.4 The weicht 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 cravity 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 x, The valid options for android:gravity include ieft, center, right, top, bottom, extical, £i11_horizontal,.and £111_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 > £411, verticai—Grows the vertical size of the object, if needed, so it completely fills its container > center zontai—Places the object in the horizontal center of its container, without changing its size > ££11_borizontal—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 hori- zontal 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: We can also combine two or more values of any attribute using the | operator. The follow- ing example centrally aligns the text horizontally and vertically within a control: android :graviny center_horizontal|center_vertical” Figure 3.5 shows the android: gravity attribute set to Jeft and right for the Button controls wango and BananaLinearLayout 109 FIGURE 3.5 The text in the Mango and Banana Button controls aligned to the left and right, respectively. through the android: gravity attribute :gravity attribute, Android provides one more similar attribute, xplore the difference between the two. ig the android: layout_gravity Attribute ty is a setting used by the view, the andvoid: 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 Bucton control, we use the android:gravity attri- bute; to align the sutton control itself in the LinearLayout (the container), we use the icy attribute. Let's add the android: layout_gravity attribute to align the succon controls themselves. To see the impact of using the android: Layout_ attribute to align the sucton controls in the LinearLayout, let’s first arrange them vertically. So, let’s modify activity_linear_layout_app.xm1 to make the Button controls appear vertically, one below the other as shown in Listing 3.5. LISTING 3.5 The activity _linear_tayout_app.xml File on Arranging the Button Controls Vertically http: //schemas .android.com/apk/res/android" al" :layout_width"match_parent* layout_height="match_parent"> ayout_width="wrap_content" andres
android: id="@+id/Banana" android: text-"Banana"410 CHAPTER 3. Laying Out Controls in Containers android: 1ayout_width="wrap_content” android: 1ayout_height="wrap_content™ /> as shown in Figure 3.6 (left) The preceding code arranges the Button controls vertically, and to the right of the To align the Button controls Mango and Banana to the center LinearLayout container, add the following statements to the respective tags in the ac ity_linear_layout_app.xml layout file: android: layout_gravity="center" and android: layout_gravity="right” 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). Q tinartayoaspptcovty E Apple vanga Banena FIGURE 3.6 (left) The three Zutton contvols vertically aligned with the ss attribute set to (middle) the Mango and Banana sutton controls aligned to the center and right od (right) the width of the three 2ucton controls expanded to take up all the evel wrap_content, of container, ani able space _wideh attribute of the three controls is set to «r2p_ ‘The width of the three controls is just enough to accommodate their content. If we now set the value of the andvoid-1aycut_wideh attribute for all three controls to = we find thet all three gutcon 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 andzoi¢: attribute to align the text within the controls. Let's add the following three attributes to the sutton controls Apple, Mango, and Banana: At the moment, the layeu id:gravitys"lefe* andvoia :gravitys"center” and ight" android:aravit These lines of code align the content of the three gutton controls to the ie¢e, 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 controlsRelativeLayout 114 expand vertically instead of horizontally as w © saw earlier, Tos following statement to the tags of all three Button controls: ve the effect, let's add the android: layout_weight="0.0" As expected, there will be no change in the height of any control, as the weight value assigned is o.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 andvoia wesaht="2.0* to all three controls results in expanding their height, 3.7 (middle), a (Cieeeyeny 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 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:aravit: "center_vertical" for the apple control android: gravity-"center_vertical |right" for the Banana control The center_vert ical 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), RelativeLayout Jn RelativeLayout, each child element is laid out in relation to other child elements; that is, the location of a child element is specified in terms of the desired distance fro existing children. To understand the concept of relative layout practically, let’s «12 CHAPTER S Laying Out Controls in Containers Tew Android project called Relativets aren fs layout fle activity setae layest_spp snl f appear as shown in Listing 3.6 USTING 3.8 The actiy aticn="vert: ical? ayout_vidth= "nat: ButtonRelativeLayout 113 android: layout_widthe"100dip" android: layout _height="wrap_content" android; layout_belows"oid/Banana" android: paddingtop-"15dip" android:paddingLeft="25dip* android:paddingRight="25dip" /> Before we understand how the controls in the previous code block are placed, let's have a quick look at different attributes used to set the positions of the layout controls. Layout Control Attributes ‘The attributes used to set the location of the control relative to a container are > android: 1ayout_alignParentTop—The top of the control is set to align with the top of the container. + : } android: layout_alignParentBotton—The bottom of the control is set to align with the bottom of the container. . > android: 1ayout_alignParentLeft—The left side of the control is set to align with the left side of the container. > android: 1ayout_alignParentRight—The right side of the control is set to align with the right side of the container. > android: ayout_centeriforizontal—The control is placed horizontally at the center of the container. . > android: ayout_centervertical—The control is placed vertically at the center of the container. — > android:layout_centerInParent—The control is placed horizontally and vertically at the center of the container.” ‘The attributes to control the position of a control in relation to other controls are > android: 1ayout_above—The control is placed above the referenced control. > android: ayout_below—The control is placed below the referenced control. > android: layout_toteftof—The control is placed to the left of the referenced control. > android: layout_torightof—The control is placed to the right of the referenced control. ‘The attributes that control the alignment of a control in relation to other controls are > android: layout_alignTop— The top of the control is set to align with the top of the referenced control.114 CHAPTER 3. Laying Out Controls in Containers android: 1ayout_alignBotton—The bottom of the control is set to align with the bottom of the referenced control. android: layout_alignbeft—The left side of the control is set to align with side of the referenced control. > android:layout_alignRight—The right side of the control is set to align w right side of the referenced control. android: 1ayout_alignBaseline—The baseline of the two controls will be aligneg re ley For spacing, Android defines two attributes: android: layout_nargin and andr: The android: layout_sargin attribute defines spacing for thé container, while android: padding defines the spacing for the view. Let’s begin with padding. > android:padding—Defines the spacing of the content on all four sides of the control. To define padding for each side individually, tse android :paddingte android:paddingRight, android: paddingTop, and android:paddingzotton. > android:paddingTop—Defines the spacing between the content and the top of the control. > android:paddingBot tom—Defines the spacing between the content and the bottom of the control. > endroid:paddingLeft—Defines the spacing between the content and the left side of the control. > endroid:paddingRight—Defines the spacing between the content and the right of the control. Here are the attributes that define the spacing between the control and the containe » android: leyout_margin—Defines the spacing of the control in relation to the Controls or the container on all four sides. To define spacing for each side indi- Vidually, we use the android: 1ayout_narginLeft, android: layout_narg android: layout_narginTop, and android: layout_marginBottom options. > android: 1eyout_nargintop—Defines the spacing between the top of the control 2%! the related control or container, } endroid:layout_marginzotto—Delines the spacing between the bottom of the control and the related control or container, > endroid:layout_narginkight—Defines the spacing between the right side of the control and the related control or container, » android: layout_marginbeft—Defines the spacing between the left side of the control and the related control or container,RelativeLayout 145 °s the controls as follows: The layout file activity relative layout_app.xm arrang ple button control is set to appear at a distance of 15dip from the top and out container, The width of the tango The 2 2oaip from the left side of the Relative button control is set to consume the available horizontal space. The text Mango appears at a distance of 2edip from all sides of the control. The Mango control Is set to appear to the right of the apple control. The control is set to appear at a distance of 1saip from the control on the left and 104ip from the right side of the relative layout container. Also, the top of the Button control Is set {0 align with the top of the container. ‘The Banana button control is assigned the wideh and height of 200dip and Sodip, respectively. The control is set to appear 15aip below the apple control. The left side of the control is set to align with the left side of the container. ‘The Grapes button control is set to appear below the Banana button control, and its width is set to expand just enough to accommodate its content. The height of the control is set to take up all available vertical space. The text Grapes is automati- cally aligned vertically; that is, it appears at the center of the vertical height when the height attribute is set to natch_parent. The minimum width of the control is set to 1004ip. The right side of the control is set to align with the right side of the container. ‘The kiwi Button control is set to appear below the Banana control. Its width is set to toodip, and the height is set to just accommodate its content. The text Kiwi is set to appear at the distance of 254ip, 2544p, and 2sdip from the top, left, and right bound- ary of the control. We don’t need to make any changes to the Relat iveLayoutappactivity. java file. Its original content is as shown in Listing 3.7. LISTING 3.7 The Default Code in the Activity File RelativeLayoutAppActivity. java _ package com.androidunleashed relativelayoutapp; import android.app.Activity; import android.os.Bundle; public class RelativeLayoutDenoactivity extends Activity ( aoverride public void onCreate (Bundle savedinstancestate) { super .onCreate (savedinstancestate) : setContentView(R. layout -act ivity_relative_layout_app) ;Ate CHAPTER 3 Laying Out Controls jan in Containers FIGURE 3.8 The five Button controls’ layout relative to each other We can make the text Grapes appear centrally at the android:gravitye "center_horizental” So, its tag appears as follows «Button The output is moditied to appe android: ide"@+id/Grapeg android: texte "Grapes" ondroid: layout_widthe"wrap content» android: leyout_heighte"match Parent ordroideminiiiatheraoodpx android: layout_aii snParentRightertrer 474s shown in Figure top row by adding the following line 3.9,Banana FIGURE 3.9 The Grapes Button control aligned horizontally at the center Let's explore the concept of laying out controls in the RelativeLayout container by writing an application. The application that we are going to create is a simple Login Form appli- cation that asks the user to enter a User 1D and Password. The Text View, EditText, and putton controls in the application are laid out in a RelativeLayout container (see Figure 3.10—left). If either the User 1D or Password is left blank, the message The User ID or paceword is left blank. Please Try Again is displayed. If the correct User 1D and Paseword, in this case, guest, are entered, then a welcome message is displayed. Otherwise, the message The User ID or password is incorrect. Please Try Again is displayed. So, let's create the application, Launch the Eclipse IDE and create a new Android appli- cation called LoginForm. Arrange four TextView controls, two Editrext controls, and a Button control in RelativeLayout, as shown in the layout file activity login_form. xml displayed in Listing 3.8. LUSTING 3.8 The activity _login_form, xml on Laying Out the TextView, EditText, and Button Controls in the RelativeLayout Container «RelativeLayout ndroide"http://schemas android. con/apk/rea/android" android: orientation="hori zontal" mnt android: layout_widthe"match parent" android: layout_heights"match_parent" >
ayout_belo” se_ID" swrap_¢ .-"250di" we+id/sign_msg" ngsid/usex_msg" sidererid/ ui :layout_height :layout_widtl :layout_below= slayout_toRightO£= singleLinesterue" /> ontent" neeid/password_mss" id text = "Passwor' swrap_content" slayout_width=' Jayout_height="wrap_content" layout _below="¢+id/user_msg" Jeyout_nargin="10dip" paédingTop="10dip"/> :ide"eid/password" layout_height="wrap_content" Hlayout_widthe"250dp* seinglebines "true" yout_belows"@+id/user_ID* Layout_toRightof "4+ id/passvord_msg" spaceworde"true" /> - “s+id/login_ button" stexte"Sign Int Jayout_widths*wrap_content* yout_height="wrap_content™ ” layout_centerHorizontal="true# android: layout_marginTop-"10dip» layout_below="6+id/password_msg"/>RelativeLayout 419 «ToxtView android: layout wldthe"mateh parent andvold layout height «"wrap content" android) {d="a9 1d/reaponae® android: Layout _below= "oi 1d/login button"/» «/Relativelayout » The controls in the application are a anged In the Relativelayout, as explained here: hrough the Text view control aign_mag, the (ext sign tn Is displayed horizontally centered at the top. IIs displayed In bold serif font, 25 dip in size. The text Is padded with a space of 1oaip on all four sides of Its container, > Another TextView control, usor_mag, displays the text User 1p below the text view aign_mag. The Textview Is placed 1od4p from all four sides, > An kaitText control user_rp Is displayed below aign_mag and to the right of user_ moa. The width assigned to the Text view control is 250 dip and is set to single-Line mode, so If the user types beyond the given width, the text scrolls to accommodate extra text but does not run over to the second line. > ATextView pasoword_mog control displaying the text Password: is displayed below the TextView user_mag. The Textview control is placed at a spacing of 1odip from all four sides, and the text Password: is displayed at 10aip from the control's top boundary, > An EaitText control panoword Is displayed below the Edit Text usex_rp and to the right of the Textview password_mag. The width assigned to the Text View control is 250 dip and is set to eingle-1ine mode, In addition, the typed characters are converted into dots for security. > Abutton control 1ogin_butten with the caption sign tn is displayed below the TextView pasoword_mag, The button is horizontally centered and is set to appear at 1odip distance from the Edit text control password, > A-rextview control reaponse Is placed below the Button login_button. It is used to display messages to the user when the sign tn button is pressed after entering User 1 and Password. To authenticate the user, we need to access the Uaer TD and Password that is entered and match these values against the valld User tb and Password, In addition, we want to Validate the kaitrext controls to confirm that none of them is blank, We also want to welcome the user if he or she Is authorized, To do all this, we welte the code in the activ- ily file Loginrormactivity. java as shown in Listing 3.9.420 CHAPTER 3. Laying Out Controls in Containers \ LUSTING 3.9 Code Written in the Java Activity Flle LoginFormactivity.java RE Mien in the Javea Activity File Logine we Package con. androidunleashed. loginform; {J import android. app. Activity import android.os Bundle; import android.view.View.onClickListener; import android.widget Button; import android.widget eaitText; import android. view. View; import android. widget .TextView; Public class LoginFormictivity extends Activity implenents OnClickListener | { Goverride Public void onCreate (Bundle savedinstancestate) { super.onCreate (savedInstancestate) ; setContentView(R. layout activity login form) ; Button b = (Button) this. findViewByIa (R.id.login_button) ; b.setOnClickListener (this) ; Public void onClick(view v) { BaitText userid = (EditText) findViewBytd(R.id.user_ID) ; PaitText password = (EditText) findViewByra(R.{d.password) ; TextView resp =| (TextView) this. findViewByTd(R. id. response) ; String usr = userid. getText() .tostring() ; String pevd’s password. getText () tostring() ; Aftuer.trin() Length()’ == 0 || povd.trim() Jength() == 0){ String str = "Mie User 1b or password is left bleak resp.setVext (str) ; , at \nPlease Try Again'i elee{ iffusr.equals(*guest*) 2& pswd.equals(" were "sy; ‘guest")) resp. setText ("Welcome cise reep.setText (the User ID or pasaword is incorrect \nPlease Tey Ageia"! } } le The eueton control is accessed from the layout file and is Mapped to the Bueton object ® an he This activity implements the onc1 ickii stener interface, Hence, the class implements t callback method enciick (), which is invoked when a click event oceuty on the Butt control. . In the onciiek() method, the user_xp and password edittext controls are accessed Pe from the layout file and mapped to the eaivtext objects useria and password. Also; vie Text View contol response is accessed from the layout file and is mapped to the Te" igAbsoluteLayout = 124. object reap. The User 1D and password entered by the user in the two Baietext controls are accessed through the objects userid and password and assigned to the two Strings usr and pewa, respectively. The data in the usr and pawd strings is checked for authentica- tion. If the user has left any of the Eait text controls blank, the message The User ID or pasword is left blank. Please Try Again is displayed, as shown in Figure 3.10 (left). Inthe User 1D and password are correct, then a welcome message is displayed (see Figure 3,10—right). Otherwise, the message The User ID or password is incorrect. Please gry Again is displayed, as shown in Figure 3.10 (middle). fa tS (2 Teme vee serio: guest eel reson Password ene ser0orpaeewor isle lane ine useri0orpasswordisincorect Pas paso Pressey agen FIGURE 3.10 (left) The Login Form displays an error if fields are left blank, (middle) the Password Incorrect message displays if the user ID or password is incorrect, and (right) the Welcome message displays when the correct user ID and password are entered. AbsoluteLayout ' Each child in an AbsoluteLayout is given a specific location within the bounds of the container. Such fixed locations make AbsoluteLayout incompatible with devices of differ- ent screen size and resolution. The controls in AbsoluteLayout are laid out by specifying their exact X and Y positions. The coordinate 0,0 is the origin and is located at the top-left corner of the screen. Let's write an application to see how controls are positioned in AbsoluteLayout. Create a new Android Project called absoluteLayoutapp. Modify its layout file, activity_ absolute_layout_app.»ml, as shown in Listing 3.10. LISTING 3.10 The Layout File activity _absolute_layout_app.xm) on Arranging Controls in the AbsoluteLayout Container
:
\geid/product_code” syrap_content” androi android: layout_y=
nyrap_content"
} android:
eBai eText android: id="6+id/product_price" android: layout_width yéroid: Layout_height android:minWidth="100dip" android: layout_x="110dip" android: layout_y="130dip" />
android: The controls in activity absolute_layout_app.xm1 are as follows: > The New Product Form TextView is set to al the top side of the container. The size of th bold. ppear 90dip from the left and 2dip from e text is set to 205p, and its style is set to > The Product Code Textview is set to a ippear Sdip from the left and aoaip from the top side of the container. » The product_code EditText control is set to aj from the top side of the container. to 100dp. PPear 110dép from the left and 30aip. The minimum width of the control is set > The ProductName TextView control is set to ay PPear Sdip from the left and soaip from the top side of the container. The product_name BaitText control is set to appear 110dip from the left and eoaip from the top side of the container. The minimum width of the control is set to 2044p, and its text is set to scroll horizontally when the user types beyond its width. The Product Price TextView is set to appear Saip from the left and 140aip from the top side of the container. The product_price EditText control is set to appear 110dip from the left and 130dip from the top side of the container. The minimum width of the control is set to 100dip. The click btn Button, Add New Product, is set to appear aoaip from the left and 190dip from the top side of the container If we don’t specify the x, y coordinates of a control in AbsoluteLayout, it is placed in the origin point, that is, at location 0,0, If the value of the x and y coordinates is too large, the control does not appear on the screen. The values of the x and y coordinates are speci- fied in any units, such as sp, in, mm, and pt. “After specifying the locations of controls in the layout file activity _absolute_layout_ app. xml, we can run the application, There is no need to make any changes in the file AbsoluteLayoutAppactivity.java, When the application is run, we get the output shown. in Figure 3.11.124 New Product Form Product Code: 107 Product Name: Camera Product Price: $50) 5 dd New Product | FIGURE 3.11 _ Different controls laid out in ‘AbsoluteLayout as it is not compatible with Android phones of The AbsoluteLayout class is not used often, different screen sizes and resolutions, ass is FrameLayout. Because we will learn to display The next layout we are going to discu i ‘ ontrol that is often used to images in FrameLayout, let’ first take a look at the Inageview C display images in Android applications. Using ImageView ‘An tmageview control is used to display images in Android applications. An image can be displayed by assigning it to the tmageview control and including the android: sxc attri- bute in the XML definition of the control. Images can also be dynamically assigned to the tmageView control through Java code. A sample ImageView tag when used in the layout file is shown here:
Rese ee Almost all attributes that we see in this XML definition should be familiar, with the excep- tion of the following ones: > gndzoid:ere Used to assign the image from drawable resources, We discuss draw- able resources in detail in Chapter 4, For now, assume that the image in the res/ drawable folder is set to display through the tmageview control via this attribute, Exampl androidisre = "@drawable/bintupic" You do not need to specify the image file extension. JPG and GIF files are supported, but the preferred image format is PNG. » android: scaleType—Used to scale an image to fit its container. The valid values for this attribute include fitxy, center, centerInside, and fitcenter. The value £itxy independently scales the image around the X and Y axes without maintaining the aspect ratio to match the size of container. The value center centers the image in the container without scaling it. The value centerInside scales the image uniformly, maintaining the aspect ratio so that the width and height of the image fit the size of its container. The value £itcenter scales the image while maintaining the aspect ratio, so that one of its X or Y axes fits the container. » android:adjustViewBounds—If set to true, the attribute adjusts the bounds of the ImageView Control to maintain the aspect ratio of the image displayed through it. > android: resizeMode—The resizeMode attribute is used to make a control resizable so we can resize it horizontally, vertically, or around both axes. We need to click and hold the control to display its resize handles. The resize handles can be dragged in the desired direction to resize the control. The available values for the resizeMode attribute include horizontal, vertical, and none. The horizontal value resizes the control around the horizontal axis, the vertical value resizes around the vertical axis, the both value resizes around both the horizontal and vertical axes, and the value none prevents resizing. FrameLayout : FrameLayout is used to display a single view. The view added to a FrameLayout is placed at the top-left edge of the layout. Any other view added to the FrameLayout overlaps the Previous view; that is, each view stacks on top of the previous one, Let's create an applica- tion to see how controls can be laid out using FrameLayout, In the application we are going to create, we will place two TnageView controls in the FameLayout container. As expected, only one tnageview will be visible, as one tmageview Will overlap the other ImageView, assuming both tmageView controls are of the same size. We will also display a button on the 1mageview, which, when selected, displays the hidden ImageView underneath.—_ 126 CHAPTER 3 Laying Out Controls in Containers payout hPP* Let's start with the application, Create a new Android project called Pram ayayatihn To display images in Android applications, the image is first copied Imo HE Ty at the folder and from there, itis referred to in the layout and other MAIS Ti detail procedure for displaying images, as well as the concept of drawable gets) 10 PE in Chapter 4, For the time being, itis enough to know that 19 Male Teas to exist referred to in the layout files placed in the rea/drawabia folder, tnt lr sanaps, im the res /azawabie folder. There are four types of drawable F010" HTN ace inanes dravable-hdpi, /res/drawable-ndpi, and /res/drawable-14P4" 1 osotutions of different resolutions and sizes in these folders. The graphics WNT NT ng ag x 36 wah api, 240dpi, 160 dpi, and 120dpi (96 x 96 px, 72 % 72 P% 4 Jocauabso-nd's and xes/ are stored in the ree/aravable-xhaps, xea/dravable haps F280 ate graphic from daravabie-1apé folders, respectively. The application picks UP Ue osez. pn Of the coirect folder. So, if we copy two images called bintwp top Macomb folders, the the preceding size and resolution and paste them into . Package Explorer resembles Figure 3.12. 2 Fomaneane = ven I 1B pecans inne Bren EB coaenseroges Zircon > olga SB ‘ emu demu bembactt E iosetuntecant [Zico mespeg LB repueycnce B porasnreves FIGURE 3.12 The Package Explorer window showing the two images, bintupic.png and bintupic2.png, dropped into the res/drawable folders To display two tmageviews and a Text View in the application, let’s write the code in the layout file activity_frame_tayeut_app. xml as shown in Listing 3.11.: Framelayout 127 4 The Layout File ING 3.14 activity tra LS ecview Controls in the FrameLayout Container o'*=*P®-#1 on Arranging neta e Fram ntainer ~anelayout ¥MINB:andvoidermec ee Speanetayout xm SP: //schemas.androia # y android:orientation="verticay Candroid:layout_width= maton, i the tmageview Parents anaroid:layout_height="natch parenyr, etnageView android:id- "@+id/first_imager android:sre = "Géravable/p android: 1ayout_width=*matr android: 1ayout_heigh intupicn ‘h_parent® match parent» sscaleTypes"fitxys /, androi cInageView android:id= "@+id/second_imagen android Src = "Gdrawable/bintupicgs dayout_width="natch parent» layout_height="match parent scaleType="titxys /, android: android: android:
"center _horizontal [bottom #333333" layout_marginBottom="1odip* /s The first_sma Bintupic. png the entire scre Mek the im, ata distance 2nd the bow, 1a datk co er selects ‘mage. For 'ge and second_image Tmageview controls are set to display the images and bintupic2. png, respectively. To make the two images stretch to cover en, the scaletype attribute in the tmageView tag is set to fitxy. A Textview, ‘age to switch, is set to display at the horizontally centered position and Of 1odip from the bottom of the container. The spacing between the text - indary of the rextview control is set to Sdip. The background ote sexs is set lor, the foreground color is set to white, anc its style is set to aul Wen a the current image on the screen, the image should satich a 3 a ye bisa this to occur, we need to write code in the activity file as shown in Listing 3.12,128 : CHAPTER 3) Laying Out Controls in Containers LISTING 3.42 Code Write inthe Java Act FUE eranetayovennoncts package con.androidunleashed. frame1ayoutaPP? import android.app.Activity; import android.os.Bundle import android.widget ImageView! fmport. android, view. View onclickiistench? import android. view. Views public clase FraneLayoutAppnctivity extends accéviey | goverride public void oncreate (Bund)e save’ w por oncreate (savesinstancestate] ; getcontentView(R. Layout er awity_frane_1ayout_*PP) 7 sewbyra (Rid -fizst_inage) final InageView first_imag? = (mageview) this - £37 jeView) this; finaviewbyta(P- ja.second_image) ; ‘final TnageView second image (imag girst_Amage.setonclickbistens? (new public void oncuick (View view) { second_inage. set Visibility (view. VISIBLE) + (view.GONB) + ainstancestate) { view setvisibility } ye second_image set0nc: public void onclick (view view) { api lity (View. VISIBLE) 7 dickbistener (new onclicknistener (1 { firet_image-setVisi jew sevvioibility (View GONE) i ye ‘The two first_image and second_image Inagevie¥ controls are located through the eae ‘method of the Activity class and assigned to the two Imageview objects: fe vase a ocd respectively. We register the click event by calling the ees ma ae od with an onchickti stener- ‘An anonymous listener is ate eer an rl events for the Imageview. When the tmageview is Skies fesees mu Ds ‘od of the listener is called. In the onclick 0) method, we sel Sy ache eae current tmageView invisible and the hidden art a erpicatonsheys applica tlon runs, we see the output shown in Figure 3.13 \ge, and the other image is hidden behind it pecause! FrameLayout one View 0\ , verlaps the oth switched, as shown in Figure 3.13 (igh, When the wer ks the mage, te IREEo | as FIGURE 3.13 (left) An image and a Text view laid out in FrameLayout, and (right) the images swith when clicked TableLayout The TableLayout is used for arranging the enclosed controls into rows and columns. Each new row in the TableLayout is defined through a TableRow object. A row can have zer0 or more controls, where each control is called a ce11. The number of columns in a TableLayout is determined by the maximum number of cells in any row. The width of a column is equal to the widest cell in that column. All elements are aligned in a column; that is, the width of all the controls increases if the width of any control in the column is increased. t Srerations Applicable to TableLayout . Wecan perfon i m several operations on TableLayout columns, incluti Collapsin , and spanning columns. g stretching, shrink- tite Columns fault w e widest c ve ca Stretch, pe width of a column is set equal to the width of the widest column, but we can © column(s) to take up available free space using the android: stretchColuans a130 CHAPTER 3 Laying Out Controls in Containers attribute in the TableLayout. The value assigned to tl Gate a Single column number or a comma-delimited list of column numbers: The sP% columns are stretched to take up any available space on the 704: : Examples: column (because the column numbers »1"—The. second C z available space in the row. jest and second columns are stretched to > android:stretchColumnss' are zero-based) is stretched to take up an! 4o,1*—Both the fi row. jumns are stretched to > android:stretchColumns=' take up the available space in the »«e—All col take up the available }» android:stretchColumns= space. Shrinking Columns We can shrink or reduce the width of the attribute in the TableLayout. We can speci Iist of column numbers for this attribute: The conte wraps to reduce their width. column(s) using the android: shrinkColumns fy either a single column oF 4 comma-delimited ‘nt in the specified columns word. the controls are not word-wrapped. By default, Examples: The first column’s width shrinks or reduces by word: > android: shrinkColumne=' wrapping its content. > android:shrinkcolunne=*#+—The content of all columns is word-wrapped to shrink their widths. Collapsing Columns We can make the column(s) collapse ot become invisible through the android: gol tepestoleens ate in the TableLayout. We can specify one or more comma-delitt Hedeotumns fo) is attribute. These columns are part of the table information but ae also make column(s) visible and invisible through coding by passing Boolean values false and true, respectively, to t ‘olumnCollapsed () me! 7 tively, to the sete: ( od > android:collapseColumn, 0*—The first column appears collapsed; that is, t 8 part of the table but is invisil invisible. isil : setColumnCollapsed() method. hago ee ogponning COMMAS tan make a colwMN span oF take up the glayout_epan attribute. The value saxon 1 2797, the following value makes the control t exam! anaroid: 13) yout_epane"2" at's try arranging controls in a Tablelayout with an example, oject called TabletayoutApp. Make its layout file aor 4 Jppear as shown in Listing 3.13, LsTING 3.13 The Layout File acts Te pleLayout Container TableLayout Create a new Android vty table layout app. zm) crableLayout wnlng:android= "http: //acheman.android.com/apk/rew/andeoia" android:orientation=" ertical” android: layout_widthe"match parent android: layout_height="natch_parent android:stretchColumng="1"> aableRow android:padding="sdip"> eTextview android: layout_height="«ap_content” android:text="New Product Form" « android: typefaces "serif" android: layout_spane"2" android:gray: cents horizontal" android:textSizes"Z0dip" /> Rows ew android: layout_height="wrap_content" te"product Code android:t android: layout_column="0"/> 2 baie Tent android:ide"9+i0d/prod_code" android: layaut,_height«twrap_cont android:layout_columne"1"/+
Sedat Aste
eTextView android: layout_row="0" android: Layout_column="0" android:text="New Product Form" android: typefaces"serif" android: layout_columnSpan="2" android: layout_gravity="center_horizontal" android:textSize="20dip" />
I> p> [>136 CHAPTER 3_Laying Out Controls in Containers.
on
A button control with the caption "cance1" is set to appear at the seventh row and second column of the grid. There is no need to write any code in the Java activity file Griduayoutappactivity.java. When the application is run, the controls are laid out in the grid pattern as shown in Figure 3.15. New Product Form Product Code: Product Name: Add Product | Cancel | FIGURE 3.15 Controls organized in the GridLayout
You might also like
Android Programming PPT To Teach 2024
PDF
No ratings yet
Android Programming PPT To Teach 2024
75 pages
Mobile Computing: Waqas Tariq Dar Spring 2021, GIFT University
PDF
No ratings yet
Mobile Computing: Waqas Tariq Dar Spring 2021, GIFT University
9 pages
III b.tech II Sem Mad Unit-3 Lecture Notes
PDF
No ratings yet
III b.tech II Sem Mad Unit-3 Lecture Notes
84 pages
Layouts
PDF
No ratings yet
Layouts
37 pages
layout
PDF
No ratings yet
layout
180 pages
Week 4 User Interface Widgets
PDF
No ratings yet
Week 4 User Interface Widgets
26 pages
Layouts: Organizing The Screen Main Layout Strategies: Android Apps Programming
PDF
No ratings yet
Layouts: Organizing The Screen Main Layout Strategies: Android Apps Programming
5 pages
Lab 4
PDF
No ratings yet
Lab 4
33 pages
Designing User Interfaces With Layouts-1
PDF
No ratings yet
Designing User Interfaces With Layouts-1
17 pages
2 Layout
PDF
No ratings yet
2 Layout
24 pages
UNIT-3 Android User Interface
PDF
No ratings yet
UNIT-3 Android User Interface
49 pages
3.3,3.4,3.5.1 Linear Layout
PDF
No ratings yet
3.3,3.4,3.5.1 Linear Layout
8 pages
Android - UI Layouts
PDF
No ratings yet
Android - UI Layouts
6 pages
Layouts in android Layouts in android Layouts in android
PDF
No ratings yet
Layouts in android Layouts in android Layouts in android
55 pages
Layout Managers
PDF
No ratings yet
Layout Managers
27 pages
Understanding The Components of A Screen
PDF
100% (2)
Understanding The Components of A Screen
5 pages
Android Ui Design
PDF
No ratings yet
Android Ui Design
58 pages
JFDP - Android App Developement Using Java PPT4
PDF
No ratings yet
JFDP - Android App Developement Using Java PPT4
31 pages
Chapter 3
PDF
No ratings yet
Chapter 3
6 pages
Unit 3
PDF
No ratings yet
Unit 3
48 pages
30dc094a8caf4fb2be8ff953e04a3d12
PDF
No ratings yet
30dc094a8caf4fb2be8ff953e04a3d12
20 pages
Getting To Know The Android User Interface
PDF
No ratings yet
Getting To Know The Android User Interface
66 pages
Android M-3
PDF
No ratings yet
Android M-3
14 pages
MP - Chapter 3
PDF
No ratings yet
MP - Chapter 3
46 pages
BCA 6th Sem Mobile Programming
PDF
100% (1)
BCA 6th Sem Mobile Programming
6 pages
Layouts
PDF
No ratings yet
Layouts
35 pages
AND1
PDF
No ratings yet
AND1
41 pages
Understanding The Components of A Screen
PDF
No ratings yet
Understanding The Components of A Screen
82 pages
Unit-2 - Chapter - 1 - MAD
PDF
100% (1)
Unit-2 - Chapter - 1 - MAD
26 pages
MAD Unit - 2
PDF
No ratings yet
MAD Unit - 2
92 pages
Lesson 5 - Supplement 1 - Basic Widgets
PDF
No ratings yet
Lesson 5 - Supplement 1 - Basic Widgets
77 pages
Android - Interface and Layout: L. Grewe
PDF
No ratings yet
Android - Interface and Layout: L. Grewe
48 pages
L02 - Android Layout (ITP4501) 2020
PDF
No ratings yet
L02 - Android Layout (ITP4501) 2020
56 pages
UNIT 2 Mobile Application Development
PDF
No ratings yet
UNIT 2 Mobile Application Development
56 pages
Lesson 5
PDF
No ratings yet
Lesson 5
24 pages
Android Layouts
PDF
No ratings yet
Android Layouts
17 pages
Unit III.pptx
PDF
No ratings yet
Unit III.pptx
14 pages
Widgets and Layouts
PDF
No ratings yet
Widgets and Layouts
17 pages
Unit 3
PDF
No ratings yet
Unit 3
64 pages
Android Layout
PDF
No ratings yet
Android Layout
28 pages
Chapter4 Designing The User Interface
PDF
No ratings yet
Chapter4 Designing The User Interface
66 pages
User Interface and Layouts
PDF
No ratings yet
User Interface and Layouts
48 pages
Unit 5
PDF
No ratings yet
Unit 5
30 pages
Android - UI Layouts: Nilesh Kumar
PDF
No ratings yet
Android - UI Layouts: Nilesh Kumar
7 pages
Ch3
PDF
No ratings yet
Ch3
6 pages
How-To Create UI Using DroidDraw
PDF
No ratings yet
How-To Create UI Using DroidDraw
12 pages
UNIT-III
PDF
No ratings yet
UNIT-III
55 pages
Unit3 Android Programming
PDF
No ratings yet
Unit3 Android Programming
16 pages
Unit6 Android
PDF
No ratings yet
Unit6 Android
4 pages
unit,-ii
PDF
No ratings yet
unit,-ii
65 pages
Comp042 Midterm
PDF
No ratings yet
Comp042 Midterm
14 pages
Android UI Lecture Layout
PDF
No ratings yet
Android UI Lecture Layout
33 pages
LinearLayout and Its Important Attributes GG With Examples in Android
PDF
No ratings yet
LinearLayout and Its Important Attributes GG With Examples in Android
8 pages
Chapter 2-MP
PDF
No ratings yet
Chapter 2-MP
35 pages
Week_2_Basic_Application
PDF
No ratings yet
Week_2_Basic_Application
42 pages
Android - Interface and Layout: L. Grewe
PDF
No ratings yet
Android - Interface and Layout: L. Grewe
48 pages
CH1 2
PDF
No ratings yet
CH1 2
27 pages
MAD9
PDF
No ratings yet
MAD9
29 pages