• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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>From the <code>res/layout/</code> directory, open the
75    <code>activity_main.xml</code> file.
76    <p>This XML file defines the layout of your activity. It contains the
77      default "Hello World" text view.</p>
78  </li>
79  <li>When you open a layout file, you’re first shown the design editor in the
80    <a href="/studio/write/layout-editor.html">Layout Editor</a>. For this lesson,
81    you work directly with the XML, so click the <b>Text</b> tab to switch to
82    the text editor.
83  </li>
84  <li>Replace the contents of the file with the following XML:
85    <pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
86&lt;LinearLayout
87    xmlns:android="http://schemas.android.com/apk/res/android"
88    xmlns:tools="http://schemas.android.com/tools"
89    android:layout_width="match_parent"
90    android:layout_height="match_parent"
91    android:orientation="horizontal"&gt;
92&lt;/LinearLayout&gt;
93</pre>
94
95  </li>
96
97</ol>
98
99<p>{@link android.widget.LinearLayout} is a view group (a subclass of {@link
100android.view.ViewGroup}) that lays out child views in either a vertical or horizontal orientation,
101as specified by the <a
102href="{@docRoot}reference/android/widget/LinearLayout.html#attr_android:orientation">{@code
103android:orientation}</a> attribute. Each child of a {@link android.widget.LinearLayout} appears on
104the screen in the order in which it appears in the XML.</p>
105
106<p>Two other attributes, <a
107href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
108android:layout_width}</a> and <a
109href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
110android:layout_height}</a>, are required for all views in order to specify their size.</p>
111
112<p>Because the {@link android.widget.LinearLayout} is the root view in the layout, it should fill
113the entire screen area that's
114available to the app by setting the width and height to
115<code>"match_parent"</code>. This value declares that the view should expand its width
116or height to <em>match</em> the width or height of the parent view.</p>
117
118<p>For more information about layout properties, see the <a
119href="{@docRoot}guide/topics/ui/declaring-layout.html">Layout</a> guide.</p>
120
121
122<h2 id="TextInput">Add a Text Field</h2>
123
124<p>In the <code>activity_main.xml</code> file, within the
125{@link android.widget.LinearLayout &lt;LinearLayout>} element, add the following
126{@link android.widget.EditText &lt;EditText>} element:</p>
127
128<pre>&lt;LinearLayout
129    xmlns:android="http://schemas.android.com/apk/res/android"
130    xmlns:tools="http://schemas.android.com/tools"
131    android:layout_width="match_parent"
132    android:layout_height="match_parent"
133    android:orientation="horizontal"&gt;
134    <b>&lt;EditText android:id="@+id/edit_message"
135        android:layout_width="wrap_content"
136        android:layout_height="wrap_content"
137        android:hint="@string/edit_message" /></b>
138&lt;/LinearLayout&gt;
139</pre>
140
141<p>Here is a description of the attributes in the
142  {@link android.widget.EditText &lt;EditText>} you added:</p>
143
144<dl>
145<dt><a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a></dt>
146<dd>This provides a unique identifier for the view, which you can use to reference the object
147from your app code, such as to read and manipulate the object (you'll see this in the next
148lesson).
149
150<p>The at sign (<code>&#64;</code>) is required when you're referring to any resource object from
151XML. It is followed by the resource type ({@code id} in this case), a slash, then the resource name
152({@code edit_message}).</p>
153
154<div class="sidebox-wrapper">
155<div class="sidebox">
156  <h3>Resource Objects</h3>
157  <p>A resource object is a unique integer name that's associated with an app resource,
158such as a bitmap, layout file, or string.</p>
159  <p>Every resource has a
160corresponding resource object defined in your project's {@code gen/R.java} file. You can use the
161object names in the {@code R} class to refer to your resources, such as when you need to specify a
162string value for the <a
163href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code android:hint}</a>
164attribute. You can also create arbitrary resource IDs that you associate with a view using the <a
165href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a> attribute,
166which allows you to reference that view from other code.</p>
167  <p>The SDK tools generate the {@code R.java} file each time you compile your app. You should never
168modify this file by hand.</p>
169  <p>For more information, read the guide to <a
170href="{@docRoot}guide/topics/resources/providing-resources.html">Providing Resources</a>.</p>
171</div>
172</div>
173
174<p>The plus sign (<code>+</code>) before the resource type is needed only when you're defining a
175resource ID for the first time. When you compile the app,
176the SDK tools use the ID name to create a new resource ID in
177your project's {@code gen/R.java} file that refers to the {@link
178android.widget.EditText} element. With the resource ID declared once this way,
179other references to the ID do not
180need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not
181needed for concrete resources such as strings or layouts. See the sidebox for
182more information about resource objects.</p></dd>
183
184<dt><a
185href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
186android:layout_width}</a> and <a
187href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
188android:layout_height}</a></dt>
189<dd>Instead of using specific sizes for the width and height, the <code>"wrap_content"</code> value
190specifies that the view should be only as big as needed to fit the contents of the view. If you
191were to instead use <code>"match_parent"</code>, then the {@link android.widget.EditText}
192element would fill the screen, because it would match the size of the parent {@link
193android.widget.LinearLayout}. For more information, see the <a
194href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts</a> guide.</dd>
195
196<dt><a
197href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code
198android:hint}</a></dt>
199<dd>This is a default string to display when the text field is empty. Instead of using a hard-coded
200string as the value, the {@code "@string/edit_message"} value refers to a string resource defined in
201a separate file. Because this refers to a concrete resource (not just an identifier), it does not
202need the plus sign. However, because you haven't defined the string resource yet, you’ll see a
203compiler error at first. You'll fix this in the next section by defining the string.
204<p class="note"><strong>Note:</strong> This string resource has the same name as the element ID:
205{@code edit_message}. However, references
206to resources are always scoped by the resource type (such as {@code id} or {@code string}), so using
207the same name does not cause collisions.</p>
208</dd>
209</dl>
210
211<h2 id="Strings">Add String Resources</h2>
212
213<p>By default, your Android project includes a string resource file at
214<code>res/values/strings.xml</code>. Here, you'll add two new strings.</p>
215
216<ol>
217<li>From the <code>res/values/</code> directory, open <code>strings.xml</code>.</li>
218<li>Add two strings so that your file looks like this:
219<pre>&lt;?xml version="1.0" encoding="utf-8"?>
220&lt;resources>
221    &lt;string name="app_name">My First App&lt;/string>
222    <b>&lt;string name="edit_message">Enter a message&lt;/string>
223    &lt;string name="button_send">Send&lt;/string></b>
224&lt;/resources>
225</pre>
226</li>
227</ol>
228
229<p>For text in the user interface, always specify each string as
230a resource. String resources allow you to manage all UI text in a single location,
231which makes the text easier to find and update. Externalizing the strings also allows you to
232localize your app to different languages by providing alternative definitions for each
233string resource.</p>
234
235<p>For more information about using string resources to localize your app for other languages,
236see the <a
237href="{@docRoot}training/basics/supporting-devices/index.html">Supporting Different Devices</a>
238class.</p>
239
240
241<h2 id="Button">Add a Button</h2>
242
243<p>Go back to the <code>activity_main.xml</code> file and add a button after the
244  {@link android.widget.EditText &lt;EditText>}. Your file should look like this:</p>
245<pre>&lt;LinearLayout
246    xmlns:android="http://schemas.android.com/apk/res/android"
247    xmlns:tools="http://schemas.android.com/tools"
248    android:orientation="horizontal"
249    android:layout_width="match_parent"
250    android:layout_height="match_parent"&gt;
251        &lt;EditText android:id="@+id/edit_message"
252          android:layout_width="wrap_content"
253          android:layout_height="wrap_content"
254          android:hint="@string/edit_message" /&gt;
255        <b>&lt;Button
256          android:layout_width="wrap_content"
257          android:layout_height="wrap_content"
258          android:text="@string/button_send" /&gt;</b>
259&lt;/LinearLayout&gt;
260</pre>
261
262<p class="note"><strong>Note:</strong> This button doesn't need the
263<a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a>
264attribute, because it won't be referenced from the activity code.</p>
265
266<p>The layout is currently designed so that both the {@link android.widget.EditText} and {@link
267android.widget.Button} widgets are only as big as necessary to fit their content, as figure 2 shows.
268</p>
269
270<img src="{@docRoot}images/training/firstapp/edittext_wrap.png" />
271<p class="img-caption"><strong>Figure 2.</strong> The {@link android.widget.EditText} and {@link
272android.widget.Button} widgets have their widths set to
273<code>"wrap_content"</code>.</p>
274
275<p>This works fine for the button, but not as well for the text field, because the user might type
276something longer. It would be nice to fill the unused screen width
277with the text field. You can do this inside a
278{@link android.widget.LinearLayout} with the <em>weight</em> property, which
279you can specify using the <a
280href="{@docRoot}reference/android/widget/LinearLayout.LayoutParams.html#weight">{@code
281android:layout_weight}</a> attribute.</p>
282
283<p>The weight value is a number that specifies the amount of remaining space each view should
284consume,
285relative to the amount consumed by sibling views. This works kind of like the
286amount of ingredients in a drink recipe: "2
287parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give
288one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of
289the remaining space and the second view fills the rest. If you add a third view and give it a weight
290of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining
291two each get 1/4.</p>
292
293<p>The default weight for all views is 0, so if you specify any weight value
294greater than 0 to only one view, then that view fills whatever space remains after all views are
295given the space they require.</p>
296
297<h2 id="Weight">Make the Input Box Fill in the Screen Width</h2>
298
299<p>In <code>activity_main.xml</code>, modify the
300  {@link android.widget.EditText &lt;EditText>} so that the attributes look like
301  this:</p>
302
303<pre>
304&lt;EditText android:id="@+id/edit_message"
305    <b>android:layout_weight="1"
306    android:layout_width="0dp"</b>
307    android:layout_height="wrap_content"
308    android:hint="@string/edit_message" /&gt;
309</pre>
310
311<p>Setting the width to zero (0dp) improves layout performance because using
312<code>"wrap_content"</code> as the width requires the system to calculate a width that is
313ultimately irrelevant because the weight value requires another width calculation to fill the
314remaining space.</p>
315
316<img src="{@docRoot}images/training/firstapp/edittext_gravity.png" />
317<p class="img-caption"><strong>Figure 3.</strong> The {@link android.widget.EditText} widget is
318given all the layout weight, so it fills the remaining space in the {@link
319android.widget.LinearLayout}.</p>
320
321<p>Here’s how your complete <code>activity_main.xml</code>layout file should now look:</p>
322
323<pre>&lt;?xml version="1.0" encoding="utf-8"?&gt;
324&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
325   xmlns:tools="http://schemas.android.com/tools"
326   android:orientation="horizontal"
327   android:layout_width="match_parent"
328   android:layout_height="match_parent"&gt;
329    &lt;EditText android:id="@+id/edit_message"
330        android:layout_weight="1"
331        android:layout_width="0dp"
332        android:layout_height="wrap_content"
333        android:hint="@string/edit_message" />
334    &lt;Button
335        android:layout_width="wrap_content"
336        android:layout_height="wrap_content"
337        android:text="@string/button_send" />
338&lt;/LinearLayout>
339</pre>
340
341<h2>Run Your App</h2>
342
343<p>This layout is applied by the default {@link android.app.Activity} class
344that the SDK tools generated when you created the project.</p>
345
346<p>To run the app and see the results,
347  click <strong>Run 'app'</strong>
348    <img src="{@docRoot}images/tools/as-run.png"
349    style="vertical-align:baseline;margin:0; max-height:1em" /> in the
350    toolbar.</p>
351
352<p>Continue to the <a href="starting-activity.html">next
353lesson</a> to learn how to respond to button presses, read content
354from the text field, start another activity, and more.</p>