Home | History | Annotate | Download | only in firstapp
      1 page.title=Building a Simple User Interface
      2 trainingnavtop=true
      3 
      4 page.tags=ui
      5 helpoutsWidget=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
     34 button. In the next lesson, your app responds when the button is pressed by sending the
     35 content 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
     38 android.view.View} and {@link android.view.ViewGroup} objects. {@link android.view.View} objects are
     39 usually 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
     42 invisible view containers that define how the child views are laid out, such as in a
     43 grid or a vertical list.</p>
     44 
     45 <p>Android provides an XML vocabulary that corresponds to the subclasses of {@link
     46 android.view.View} and {@link android.view.ViewGroup} so you can define your UI in XML using
     47 a hierarchy of UI elements.</p>
     48 
     49 <p>Layouts are subclasses of the {@link android.view.ViewGroup}. In this exercise, you'll work with
     50 a {@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,
     56 but it's especially important so you can create different layouts for
     57 different screen sizes. For example, you can create two versions of a layout and tell
     58 the system to use one on "small" screens and the other on "large" screens. For more information,
     59 see the class about <a
     60 href="{@docRoot}training/basics/supporting-devices/index.html">Supporting Different
     61 Devices</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
     67 android.view.ViewGroup} objects form branches in the layout and contain other {@link
     68 android.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>activity_my.xml</code>
     75 file.
     76 <p>The BlankActivity template you chose when you created this project includes the
     77 <code>activity_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, youre first shown
     83     the Preview pane. Clicking elements in this pane opens the WYSIWYG tools in the Design pane. For
     84     this lesson, youre 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 <p class="code-caption">res/layout/activity_my.xml</p>
     96 <pre>
     97 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     98     xmlns:tools="http://schemas.android.com/tools"
     99     android:layout_width="match_parent"
    100     android:layout_height="match_parent"
    101     android:orientation="horizontal" >
    102 &lt;/LinearLayout>
    103 </pre>
    104 
    105 <p>{@link android.widget.LinearLayout} is a view group (a subclass of {@link
    106 android.view.ViewGroup}) that lays out child views in either a vertical or horizontal orientation,
    107 as specified by the <a
    108 href="{@docRoot}reference/android/widget/LinearLayout.html#attr_android:orientation">{@code
    109 android:orientation}</a> attribute. Each child of a {@link android.widget.LinearLayout} appears on
    110 the screen in the order in which it appears in the XML.</p>
    111 
    112 <p>Two other attributes, <a
    113 href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
    114 android:layout_width}</a> and <a
    115 href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
    116 android:layout_height}</a>, are required for all views in order to specify their size.</p>
    117 
    118 <p>Because the {@link android.widget.LinearLayout} is the root view in the layout, it should fill
    119 the entire screen area that's
    120 available to the app by setting the width and height to
    121 <code>"match_parent"</code>. This value declares that the view should expand its width
    122 or height to <em>match</em> the width or height of the parent view.</p>
    123 
    124 <p>For more information about layout properties, see the <a
    125 href="{@docRoot}guide/topics/ui/declaring-layout.html">Layout</a> guide.</p>
    126 
    127 
    128 <h2 id="TextInput">Add a Text Field</h2>
    129 
    130 <p>As with every {@link android.view.View} object, you must define certain XML attributes to specify
    131 the {@link android.widget.EditText} object's properties.</p>
    132 
    133 <ol>
    134 <li>In the <code>activity_my.xml</code> file, within the
    135 {@link android.widget.LinearLayout &lt;LinearLayout>} element, define an
    136 {@link android.widget.EditText &lt;EditText>} element with the <code>id</code> attribute
    137 set to <code>@+id/edit_message</code>.</li>
    138 <li>Define the <code>layout_width</code> and <code>layout_height</code> attributes as
    139 <code>wrap_content</code>.</li>
    140 <li>Define a <code>hint</code> attribute as a string object named <code>edit_message</code>.</li>
    141 </ol>
    142 
    143 <p>The {@link android.widget.EditText &lt;EditText>} element should read as follows:</p>
    144 
    145 <p class="code-caption">res/layout/activity_my.xml</p>
    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
    158 from your app code, such as to read and manipulate the object (you'll see this in the next
    159 lesson).
    160 
    161 <p>The at sign (<code>&#64;</code>) is required when you're referring to any resource object from
    162 XML. 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,
    169 such as a bitmap, layout file, or string.</p>
    170   <p>Every resource has a
    171 corresponding resource object defined in your project's {@code gen/R.java} file. You can use the
    172 object names in the {@code R} class to refer to your resources, such as when you need to specify a
    173 string value for the <a
    174 href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code android:hint}</a>
    175 attribute. You can also create arbitrary resource IDs that you associate with a view using the <a
    176 href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a> attribute,
    177 which 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
    179 modify this file by hand.</p>
    180   <p>For more information, read the guide to <a
    181 href="{@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
    186 resource ID for the first time. When you compile the app,
    187 the SDK tools use the ID name to create a new resource ID in
    188 your project's {@code gen/R.java} file that refers to the {@link
    189 android.widget.EditText} element. With the resource ID declared once this way,
    190 other references to the ID do not
    191 need the plus sign. Using the plus sign is necessary only when specifying a new resource ID and not
    192 needed for concrete resources such as strings or layouts. See the sidebox for
    193 more information about resource objects.</p></dd>
    194 
    195 <dt><a
    196 href="{@docRoot}reference/android/view/View.html#attr_android:layout_width">{@code
    197 android:layout_width}</a> and <a
    198 href="{@docRoot}reference/android/view/View.html#attr_android:layout_height">{@code
    199 android:layout_height}</a></dt>
    200 <dd>Instead of using specific sizes for the width and height, the <code>"wrap_content"</code> value
    201 specifies that the view should be only as big as needed to fit the contents of the view. If you
    202 were to instead use <code>"match_parent"</code>, then the {@link android.widget.EditText}
    203 element would fill the screen, because it would match the size of the parent {@link
    204 android.widget.LinearLayout}. For more information, see the <a
    205 href="{@docRoot}guide/topics/ui/declaring-layout.html">Layouts</a> guide.</dd>
    206 
    207 <dt><a
    208 href="{@docRoot}reference/android/widget/TextView.html#attr_android:hint">{@code
    209 android:hint}</a></dt>
    210 <dd>This is a default string to display when the text field is empty. Instead of using a hard-coded
    211 string as the value, the {@code "@string/edit_message"} value refers to a string resource defined in
    212 a separate file. Because this refers to a concrete resource (not just an identifier), it does not
    213 need the plus sign. However, because you haven't defined the string resource yet, youll see a
    214 compiler 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
    217 to resources are always scoped by the resource type (such as {@code id} or {@code string}), so using
    218 the 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 <li>Remove the line for the <code>"hello world"</code> string.</li>
    236 </ol>
    237 
    238 <p>The result for <code>strings.xml</code> looks like this:</p>
    239 
    240 <p class="code-caption">res/values/strings.xml</p>
    241 <pre>
    242 &lt;?xml version="1.0" encoding="utf-8"?>
    243 &lt;resources>
    244     &lt;string name="app_name">My First App&lt;/string>
    245     &lt;string name="edit_message">Enter a message&lt;/string>
    246     &lt;string name="button_send">Send&lt;/string>
    247     &lt;string name="action_settings">Settings&lt;/string>
    248     &lt;string name="title_activity_main">MainActivity&lt;/string>
    249 &lt;/resources>
    250 </pre>
    251 
    252 <p>For text in the user interface, always specify each string as
    253 a resource. String resources allow you to manage all UI text in a single location,
    254 which makes the text easier to find and update. Externalizing the strings also allows you to
    255 localize your app to different languages by providing alternative definitions for each
    256 string resource.</p>
    257 
    258 <p>For more information about using string resources to localize your app for other languages,
    259 see the <a
    260 href="{@docRoot}training/basics/supporting-devices/index.html">Supporting Different Devices</a>
    261 class.</p>
    262 
    263 
    264 <h2 id="Button">Add a Button</h2>
    265 
    266 <ol>
    267 <li>In Android Studio, from the <code>res/layout</code> directory, edit the <code>activity_my.xml</code>
    268 file.</li>
    269 <li>Within the
    270 {@link android.widget.LinearLayout &lt;LinearLayout>} element, define a
    271 {@link android.widget.Button &lt;Button>} element immediately following the
    272 {@link android.widget.EditText &lt;EditText>} element.</li>
    273 <li>Set the button's width and height attributes to <code>"wrap_content"</code> so
    274 the button is only as big as necessary to fit the button's text label.</li>
    275 <li>Define the button's text label with the <a
    276 href="{@docRoot}reference/android/widget/TextView.html#attr_android:text">{@code
    277 android:text}</a> attribute; set its value to the <code>button_send</code> string
    278 resource you defined in the previous section.</li>
    279 </ol>
    280 
    281 <p>Your {@link android.widget.LinearLayout &lt;LinearLayout>} should look like this:</p>
    282 
    283 <p class="code-caption">res/layout/activity_my.xml</p>
    284 <pre>
    285 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    286     xmlns:tools="http://schemas.android.com/tools"
    287     android:layout_width="match_parent"
    288     android:layout_height="match_parent"
    289     android:orientation="horizontal" &gt;
    290       &lt;EditText android:id="@+id/edit_message"
    291         android:layout_width="wrap_content"
    292         android:layout_height="wrap_content"
    293         android:hint="@string/edit_message" /&gt;
    294       &lt;Button
    295         android:layout_width="wrap_content"
    296         android:layout_height="wrap_content"
    297         android:text="@string/button_send" /&gt;
    298 &lt;/LinearLayout&gt;
    299 </pre>
    300 
    301 <p class="note"><strong>Note:</strong> This button doesn't need the
    302 <a href="{@docRoot}reference/android/view/View.html#attr_android:id">{@code android:id}</a>
    303 attribute, because it won't be referenced from the activity code.</p>
    304 
    305 <p>The layout is currently designed so that both the {@link android.widget.EditText} and {@link
    306 android.widget.Button} widgets are only as big as necessary to fit their content, as shown in
    307 figure 2.</p>
    308 
    309 <img src="{@docRoot}images/training/firstapp/edittext_wrap.png" />
    310 <p class="img-caption"><strong>Figure 2.</strong> The {@link android.widget.EditText} and {@link
    311 android.widget.Button} widgets have their widths set to
    312 <code>"wrap_content"</code>.</p>
    313 
    314 <p>This works fine for the button, but not as well for the text field, because the user might type
    315 something longer. It would be nice to fill the unused screen width
    316 with the text field. You can do this inside a
    317 {@link android.widget.LinearLayout} with the <em>weight</em> property, which
    318 you can specify using the <a
    319 href="{@docRoot}reference/android/widget/LinearLayout.LayoutParams.html#weight">{@code
    320 android:layout_weight}</a> attribute.</p>
    321 
    322 <p>The weight value is a number that specifies the amount of remaining space each view should
    323 consume,
    324 relative to the amount consumed by sibling views. This works kind of like the
    325 amount of ingredients in a drink recipe: "2
    326 parts soda, 1 part syrup" means two-thirds of the drink is soda. For example, if you give
    327 one view a weight of 2 and another one a weight of 1, the sum is 3, so the first view fills 2/3 of
    328 the remaining space and the second view fills the rest. If you add a third view and give it a weight
    329 of 1, then the first view (with weight of 2) now gets 1/2 the remaining space, while the remaining
    330 two each get 1/4.</p>
    331 
    332 <p>The default weight for all views is 0, so if you specify any weight value
    333 greater than 0 to only one view, then that view fills whatever space remains after all views are
    334 given the space they require.</p>
    335 
    336 <h2 id="Weight">Make the Input Box Fill in the Screen Width</h2>
    337 
    338 <p>To fill the remaining space in your layout with the {@link android.widget.EditText} element, do
    339 the following:</p>
    340 
    341 <ol>
    342 <li>In the <code>activity_my.xml</code> file, assign the
    343 {@link android.widget.EditText &lt;EditText>} element's <code>layout_weight</code> attribute a value
    344 of <code>1</code>.</li>
    345 <li>Also, assign {@link android.widget.EditText &lt;EditText>} element's <code>layout_width</code>
    346 attribute a value of <code>0dp</code>.
    347 
    348 <p class="code-caption">res/layout/activity_my.xml</p>
    349 <pre>
    350 &lt;EditText
    351     android:layout_weight="1"
    352     android:layout_width="0dp"
    353     ... /&gt;
    354 </pre>
    355 
    356 <p>To improve the layout efficiency when you specify the weight, you should change the
    357 width of the {@link android.widget.EditText} to be
    358 zero (0dp). Setting the width to zero improves layout performance because using
    359 <code>"wrap_content"</code> as the width requires the system to calculate a width that is
    360 ultimately irrelevant because the weight value requires another width calculation to fill the
    361 remaining space.</p>
    362 
    363 <p>Figure 3
    364 shows the result when you assign all weight to the {@link android.widget.EditText} element.</p>
    365 
    366 <img src="{@docRoot}images/training/firstapp/edittext_gravity.png" />
    367 <p class="img-caption"><strong>Figure 3.</strong> The {@link android.widget.EditText} widget is
    368 given all the layout weight, so it fills the remaining space in the {@link
    369 android.widget.LinearLayout}.</p>
    370 
    371 </li>
    372 </ol>
    373 
    374 <p>Heres how your complete <code>activity_my.xml</code>layout file should now look:</p>
    375 
    376 <p class="code-caption">res/layout/activity_my.xml</p>
    377 <pre>
    378 &lt;?xml version="1.0" encoding="utf-8"?>
    379 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    380     xmlns:tools="http://schemas.android.com/tools"
    381     android:layout_width="match_parent"
    382     android:layout_height="match_parent"
    383     android:orientation="horizontal">
    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
    399 that the SDK tools generated when you created the project. Run the app to see the
    400 results:</p>
    401 
    402 <ul>
    403   <li>In Android Studio, from the toolbar, click <strong>Run</strong>
    404     <img src="{@docRoot}images/tools/as-run.png"
    405     style="vertical-align:baseline;margin:0; max-height:1em" />.</li>
    406   <li>Or from a command line, change directories to the root of your Android project and
    407 execute:
    408 <pre>
    409 ant debug
    410 adb install bin/MyFirstApp-debug.apk
    411 </pre></li>
    412 </ul>
    413 
    414 <p>Continue to the <a href="starting-activity.html">next
    415 lesson</a> to learn how to respond to button presses, read content
    416 from the text field, start another activity, and more.</p>
    417 
    418 
    419 
    420