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