1page.title=Building a Simple User Interface
2trainingnavtop=true
3
4page.tags=ui
5helpoutsWidget=true
6
7@jd:body
8
9
10<!-- This is the training bar -->
11<div id="tb-wrapper">
12<div id="tb">
13
14<h2>This lesson teaches you to</h2>
15
16<ol>
17  <li><a href="#LinearLayout">Create a Linear Layout</a></li>
18  <li><a href="#TextInput">Add a Text Field</a></li>
19  <li><a href="#Strings">Add String Resources</a></li>
20  <li><a href="#Button">Add a Button</a></li>
21  <li><a href="#Weight">Make the Input Box Fill in the Screen Width</a></li>
22</ol>
23
24
25<h2>You should also read</h2>
26<ul>
27  <li><a href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts</a></li>
28</ul>
29
30</div>
31</div>
32
33<p>In this lesson, you create a layout in XML that includes a text field and a
34button. In the next lesson, your app responds when the button is pressed by sending the
35content of the text field to another activity.</p>
36
37<p>The graphical user interface for an Android app is built using a hierarchy of {@link
38android.view.View} and {@link android.view.ViewGroup} objects. {@link android.view.View} objects are
39usually UI widgets such as <a href="{@docRoot}guide/topics/ui/controls/button.html">buttons</a> or
40<a href="{@docRoot}guide/topics/ui/controls/text.html">text fields</a>.
41{@link android.view.ViewGroup} objects are
42invisible view containers that define how the child views are laid out, such as in a
43grid or a vertical list.</p>
44
45<p>Android provides an XML vocabulary that corresponds to the subclasses of {@link
46android.view.View} and {@link android.view.ViewGroup} so you can define your UI in XML using
47a hierarchy of UI elements.</p>
48
49<p>Layouts are subclasses of the {@link android.view.ViewGroup}. In this exercise, you'll work with
50a {@link android.widget.LinearLayout}.</p>
51
52<div class="sidebox-wrapper">
53<div class="sidebox">
54  <h2>Alternative Layouts</h2>
55  <p>Declaring your UI layout in XML rather than runtime code is useful for several reasons,
56but it's especially important so you can create different layouts for
57different screen sizes. For example, you can create two versions of a layout and tell
58the system to use one on "small" screens and the other on "large" screens. For more information,
59see the class about <a
60href="{@docRoot}training/basics/supporting-devices/index.html">Supporting Different
61Devices</a>.</p>
62</div>
63</div>
64
65<img src="{@docRoot}images/viewgroup.png" alt="" width="400" height="214" />
66<p class="img-caption"><strong>Figure 1.</strong> Illustration of how {@link
67android.view.ViewGroup} objects form branches in the layout and contain other {@link
68android.view.View} objects.</p>
69
70
71<h2 id="LinearLayout">Create a Linear Layout</h2>
72
73<ol>
74<li>In Android Studio, from the <code>res/layout</code> directory, open the {@code content_my.xml}
75file.
76<p>The BlankActivity template you chose when you created this project includes the
77<code>content_my.xml</code> file with a {@link android.widget.RelativeLayout} root view and a
78{@link android.widget.TextView} child view.</p>
79</li>
80<li>In the <strong>Preview</strong> pane, click the Hide icon <img src="{@docRoot}images/tools/as-hide-side.png"
81  style="vertical-align:baseline;margin:0; max-height:1.5em" /> to close the Preview pane.
82  <p> In Android Studio, when you open a layout file, you’re first shown
83    the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For
84    this lesson, you’re going to work directly with the XML.</p></li>
85<li>Delete the {@link android.widget.TextView &lt;TextView>} element.</li>
86<li>Change the {@link android.widget.RelativeLayout &lt;RelativeLayout>} element to
87{@link android.widget.LinearLayout &lt;LinearLayout>}.</li>
88<li>Add the <a href="{@docRoot}reference/android/widget/LinearLayout.html#attr_android:orientation">
89{@code android:orientation}</a> attribute and set it to <code>"horizontal"</code>.</li>
90<li>Remove the {@code android:padding} attributes and the {@code tools:context} attribute.
91</ol>
92
93<p>The result looks like this:</p>
94
95<pre>
96&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
97    xmlns:app="http://schemas.android.com/apk/res-auto"
98    xmlns:tools="http://schemas.android.com/tools"
99    android:orientation="horizontal"
100    android:layout_width="match_parent"
101    android:layout_height="match_parent"
102    app:layout_behavior="@string/appbar_scrolling_view_behavior"
103    tools:showIn="@layout/activity_my"&gt;
104</pre>
105
106<p>{@link android.widget.LinearLayout} is a view group (a subclass of {@link
107android.view.ViewGroup}) that lays out child views in either a vertical or horizontal orientation,
108as specified by the <a
109href="{@docRoot}reference/android/widget/LinearLayout.html#attr_android:orientation">{@code
110android:orientation}</a> attribute. Each child of a {@link android.widget.LinearLayout} appears on
111the screen in the order in which it appears in the XML.</p>
112
113<p>Two other attributes, <a
114href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
115android:layout_width}</a> and <a
116href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
117android:layout_height}</a>, are required for all views in order to specify their size.</p>
118
119<p>Because the {@link android.widget.LinearLayout} is the root view in the layout, it should fill
120the entire screen area that's
121available to the app by setting the width and height to
122<code>"match_parent"</code>. This value declares that the view should expand its width
123or height to <em>match</em> the width or height of the parent view.</p>
124
125<p>For more information about layout properties, see the <a
126href="{@docRoot}guide/topics/ui/declaring-layout.html">Layout</a> guide.</p>
127
128
129<h2 id="TextInput">Add a Text Field</h2>
130
131<p>As with every {@link android.view.View} object, you must define certain XML attributes to specify
132the {@link android.widget.EditText} object's properties.</p>
133
134<ol>
135<li>In the <code>content_my.xml</code> file, within the
136{@link android.widget.LinearLayout &lt;LinearLayout>} element, define an
137{@link android.widget.EditText &lt;EditText>} element with the <code>id</code> attribute
138set to <code>@+id/edit_message</code>.</li>
139<li>Define the <code>layout_width</code> and <code>layout_height</code> attributes as
140<code>wrap_content</code>.</li>
141<li>Define a <code>hint</code> attribute as a string object named <code>edit_message</code>.</li>
142</ol>
143
144<p>The {@link android.widget.EditText &lt;EditText>} element should read as follows:</p>
145
146<pre>
147&lt;EditText android:id="@+id/edit_message"
148    android:layout_width="wrap_content"
149    android:layout_height="wrap_content"
150    android:hint="@string/edit_message" />
151</pre>
152
153<p>Here are the {@link android.widget.EditText &lt;EditText>} attributes you added:</p>
154
155<dl>
156<dt><a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a></dt>
157<dd>This provides a unique identifier for the view, which you can use to reference the object
158from your app code, such as to read and manipulate the object (you'll see this in the next
159lesson).
160
161<p>The at sign (<code>&#64;</code>) is required when you're referring to any resource object from
162XML. It is followed by the resource type ({@code id} in this case), a slash, then the resource name
163({@code edit_message}).</p>
164
165<div class="sidebox-wrapper">
166<div class="sidebox">
167  <h3>Resource Objects</h3>
168  <p>A resource object is a unique integer name that's associated with an app resource,
169such as a bitmap, layout file, or string.</p>
170  <p>Every resource has a
171corresponding resource object defined in your project's {@code gen/R.java} file. You can use the
172object names in the {@code R} class to refer to your resources, such as when you need to specify a
173string value for the <a
174href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code android:hint}</a>
175attribute. You can also create arbitrary resource IDs that you associate with a view using the <a
176href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a> attribute,
177which allows you to reference that view from other code.</p>
178  <p>The SDK tools generate the {@code R.java} file each time you compile your app. You should never
179modify this file by hand.</p>
180  <p>For more information, read the guide to <a
181href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a>.</p>
182</div>
183</div>
184
185<p>The plus sign (<code>+</code>) before the resource type is needed only when you're defining a
186resource ID for the first time. When you compile the app,
187the SDK tools use the ID name to create a new resource ID in
188your project's {@code gen/R.java} file that refers to the {@link
189android.widget.EditText} element. With the resource ID declared once this way,
190other references to the ID do not
191need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not
192needed for concrete resources such as strings or layouts. See the sidebox for
193more information about resource objects.</p></dd>
194
195<dt><a
196href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
197android:layout_width}</a> and <a
198href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
199android:layout_height}</a></dt>
200<dd>Instead of using specific sizes for the width and height, the <code>"wrap_content"</code> value
201specifies that the view should be only as big as needed to fit the contents of the view. If you
202were to instead use <code>"match_parent"</code>, then the {@link android.widget.EditText}
203element would fill the screen, because it would match the size of the parent {@link
204android.widget.LinearLayout}. For more information, see the <a
205href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts</a> guide.</dd>
206
207<dt><a
208href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code
209android:hint}</a></dt>
210<dd>This is a default string to display when the text field is empty. Instead of using a hard-coded
211string as the value, the {@code "@string/edit_message"} value refers to a string resource defined in
212a separate file. Because this refers to a concrete resource (not just an identifier), it does not
213need the plus sign. However, because you haven't defined the string resource yet, you’ll see a
214compiler error at first. You'll fix this in the next section by defining the string.
215<p class="note"><strong>Note:</strong> This string resource has the same name as the element ID:
216{@code edit_message}. However, references
217to resources are always scoped by the resource type (such as {@code id} or {@code string}), so using
218the same name does not cause collisions.</p>
219</dd>
220</dl>
221
222<h2 id="Strings">Add String Resources</h2>
223
224<p>By default, your Android project includes a string resource file at
225<code>res/values/strings.xml</code>. Here, you'll add a new string named
226<code>"edit_message"</code> and set the value to "Enter a message."</p>
227
228<ol>
229<li>In Android Studio, from the <code>res/values</code> directory, open <code>strings.xml</code>.</li>
230<li>Add a line for a string named <code>"edit_message"</code> with the value, "Enter a message".
231</li>
232<li>Add a line for a string named <code>"button_send"</code> with the value, "Send".
233<p>You'll create the button that uses this string in the next section.</p>
234</li>
235</ol>
236
237<p>The result for <code>strings.xml</code> looks like this:</p>
238
239<pre>
240&lt;?xml version="1.0" encoding="utf-8"?>
241&lt;resources>
242    &lt;string name="app_name">My First App&lt;/string>
243    &lt;string name="edit_message">Enter a message&lt;/string>
244    &lt;string name="button_send">Send&lt;/string>
245    &lt;string name="action_settings">Settings&lt;/string>
246&lt;/resources>
247</pre>
248
249<p>For text in the user interface, always specify each string as
250a resource. String resources allow you to manage all UI text in a single location,
251which makes the text easier to find and update. Externalizing the strings also allows you to
252localize your app to different languages by providing alternative definitions for each
253string resource.</p>
254
255<p>For more information about using string resources to localize your app for other languages,
256see the <a
257href="{@docRoot}training/basics/supporting-devices/index.html">Supporting Different Devices</a>
258class.</p>
259
260
261<h2 id="Button">Add a Button</h2>
262
263<ol>
264<li>In Android Studio, from the <code>res/layout</code> directory, edit the <code>content_my.xml</code>
265file.</li>
266<li>Within the
267{@link android.widget.LinearLayout &lt;LinearLayout>} element, define a
268{@link android.widget.Button &lt;Button>} element immediately following the
269{@link android.widget.EditText &lt;EditText>} element.</li>
270<li>Set the button's width and height attributes to <code>"wrap_content"</code> so
271the button is only as big as necessary to fit the button's text label.</li>
272<li>Define the button's text label with the <a
273href="{@docRoot}reference/android/widget/TextView.html#attr_android:text">{@code
274android:text}</a> attribute; set its value to the <code>button_send</code> string
275resource you defined in the previous section.</li>
276</ol>
277
278<p>Your {@link android.widget.LinearLayout &lt;LinearLayout>} should look like this:</p>
279
280<pre>
281&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
282    xmlns:app="http://schemas.android.com/apk/res-auto"
283    xmlns:tools="http://schemas.android.com/tools"
284    android:orientation="horizontal"
285    android:layout_width="match_parent"
286    android:layout_height="match_parent"
287    app:layout_behavior="@string/appbar_scrolling_view_behavior"
288    tools:showIn="@layout/activity_my"&gt;
289        &lt;EditText android:id="@+id/edit_message"
290          android:layout_width="wrap_content"
291          android:layout_height="wrap_content"
292          android:hint="@string/edit_message" /&gt;
293        &lt;Button
294          android:layout_width="wrap_content"
295          android:layout_height="wrap_content"
296          android:text="@string/button_send" /&gt;
297&lt;/LinearLayout&gt;
298</pre>
299
300<p class="note"><strong>Note:</strong> This button doesn't need the
301<a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a>
302attribute, because it won't be referenced from the activity code.</p>
303
304<p>The layout is currently designed so that both the {@link android.widget.EditText} and {@link
305android.widget.Button} widgets are only as big as necessary to fit their content, as Figure 2 shows.
306</p>
307
308<img src="{@docRoot}images/training/firstapp/edittext_wrap.png" />
309<p class="img-caption"><strong>Figure 2.</strong> The {@link android.widget.EditText} and {@link
310android.widget.Button} widgets have their widths set to
311<code>"wrap_content"</code>.</p>
312
313<p>This works fine for the button, but not as well for the text field, because the user might type
314something longer. It would be nice to fill the unused screen width
315with the text field. You can do this inside a
316{@link android.widget.LinearLayout} with the <em>weight</em> property, which
317you can specify using the <a
318href="{@docRoot}reference/android/widget/LinearLayout.LayoutParams.html#weight">{@code
319android:layout_weight}</a> attribute.</p>
320
321<p>The weight value is a number that specifies the amount of remaining space each view should
322consume,
323relative to the amount consumed by sibling views. This works kind of like the
324amount of ingredients in a drink recipe: "2
325parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give
326one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of
327the remaining space and the second view fills the rest. If you add a third view and give it a weight
328of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining
329two each get 1/4.</p>
330
331<p>The default weight for all views is 0, so if you specify any weight value
332greater than 0 to only one view, then that view fills whatever space remains after all views are
333given the space they require.</p>
334
335<h2 id="Weight">Make the Input Box Fill in the Screen Width</h2>
336
337<p>To fill the remaining space in your layout with the {@link android.widget.EditText} element, do
338the following:</p>
339
340<ol>
341<li>In the <code>content_my.xml</code> file, assign the
342{@link android.widget.EditText &lt;EditText>} element's <code>layout_weight</code> attribute a value
343of <code>1</code>.</li>
344<li>Also, assign {@link android.widget.EditText &lt;EditText>} element's <code>layout_width</code>
345attribute a value of <code>0dp</code>.
346
347<pre>
348&lt;EditText
349    android:layout_weight="1"
350    android:layout_width="0dp"
351    ... /&gt;
352</pre>
353
354<p>To improve the layout efficiency when you specify the weight, you should change the
355width of the {@link android.widget.EditText} to be
356zero (0dp). Setting the width to zero improves layout performance because using
357<code>"wrap_content"</code> as the width requires the system to calculate a width that is
358ultimately irrelevant because the weight value requires another width calculation to fill the
359remaining space.</p>
360
361<p>Figure 3
362shows the result when you assign all weight to the {@link android.widget.EditText} element.</p>
363
364<img src="{@docRoot}images/training/firstapp/edittext_gravity.png" />
365<p class="img-caption"><strong>Figure 3.</strong> The {@link android.widget.EditText} widget is
366given all the layout weight, so it fills the remaining space in the {@link
367android.widget.LinearLayout}.</p>
368
369</li>
370</ol>
371
372<p>Here’s how your complete <code>content_my.xml</code>layout file should now look:</p>
373
374<pre>
375&lt;?xml version="1.0" encoding="utf-8"?>
376&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
377   xmlns:app="http://schemas.android.com/apk/res-auto"
378   xmlns:tools="http://schemas.android.com/tools"
379   android:orientation="horizontal"
380   android:layout_width="match_parent"
381   android:layout_height="match_parent"
382   app:layout_behavior="@string/appbar_scrolling_view_behavior"
383   tools:showIn="@layout/activity_my"&gt;
384    &lt;EditText android:id="@+id/edit_message"
385        android:layout_weight="1"
386        android:layout_width="0dp"
387        android:layout_height="wrap_content"
388        android:hint="@string/edit_message" />
389    &lt;Button
390        android:layout_width="wrap_content"
391        android:layout_height="wrap_content"
392        android:text="@string/button_send" />
393&lt;/LinearLayout>
394</pre>
395
396<h2>Run Your App</h2>
397
398<p>This layout is applied by the default {@link android.app.Activity} class
399that the SDK tools generated when you created the project.</p>
400
401<p>To run the app and see the results,
402  click <strong>Run 'app'</strong>
403    <img src="{@docRoot}images/tools/as-run.png"
404    style="vertical-align:baseline;margin:0; max-height:1em" /> in the
405    toolbar.</p>
406
407<p>Continue to the <a href="starting-activity.html">next
408lesson</a> to learn how to respond to button presses, read content
409from the text field, start another activity, and more.</p>
410
411
412
413