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