1.2: Layouts and resources for the UI


This chapter describes the screen's user interface (UI) layout and other resources you create for your app, and the code you would use to respond to a user's tap of a UI element.


The UI consists of a hierarchy of objects called views — every element of the screen is a View. The View class represents the basic building block for all UI components, and the base class for classes that provide interactive UI components such as buttons, checkboxes, and text entry fields.

A View has a location, expressed as a pair of left and top coordinates, and two dimensions, expressed as a width and a height. The unit for location and dimensions is the density-independent pixel (dp).

The Android system provides hundreds of predefined View subclasses. Commonly used View subclasses described over several lessons include:

You can define a View to appear on the screen and respond to a user tap. A View can also be defined to accept text input, or to be invisible until needed.

You can specify View elements in layout resource files. Layout resources are written in XML and listed within the layout folder in the res folder in the Project > Android pane.

ViewGroup groups

View elements can be grouped inside a ViewGroup, which acts as a container. The relationship is parent-child, in which the parent is a ViewGroup, and the child is a View or another ViewGroup. The following are commonly used ViewGroup groups:

  • ConstraintLayout: A group that places UI elements (child View elements) using constraint connections to other elements and to the layout edges (parent View).
  • ScrollView: A group that contains one other child View element and enables scrolling the child View element.
  • RecyclerView: A group that contains a list of other View elements or ViewGroup groups and enables scrolling them by adding and removing View elements dynamically from the screen.

Layout ViewGroup groups

The View elements for a screen are organized in a hierarchy. At the root of this hierarchy is a ViewGroup that contains the layout of the entire screen. The ViewGroup can contain child View elements or other ViewGroup groups as shown in the following figure.  The View hierarchy

In the figure above:

  1. The root ViewGroup.
  2. The first set of child View elements and ViewGroup groups whose parent is the root.

Some ViewGroup groups are designated as layouts because they organize child View elements in a specific way and are typically used as the root ViewGroup. Some examples of layouts are:

  • ConstraintLayout: A group of child View elements using constraints, edges, and guidelines to control how the elements are positioned relative to other elements in the layout. ConstraintLayout was designed to make it easy to click and drag View elements in the layout editor.
  • LinearLayout: A group of child View elements positioned and aligned horizontally or vertically.
  • RelativeLayout: A group of child View elements in which each element is positioned and aligned relative to other elements within the ViewGroup. In other words, the positions of the child View elements can be described in relation to each other or to the parent ViewGroup.
  • TableLayout: A group of child View elements arranged into rows and columns.
  • FrameLayout: A group of child View elements in a stack. FrameLayout is designed to block out an area on the screen to display one View. Child View elements are drawn in a stack, with the most recently added child on top. The size of the FrameLayout is the size of its largest child View element.
  • GridLayout: A group that places its child View elements in a rectangular grid that can be scrolled.  Visual representations of layouts

Tip: Learn more about different layout types in Common Layout Objects.

A simple example of a LinearLayout with child View elements is shown below as a diagram of the layout file (activity_main.xml), along with a hierarchy diagram (top right) and a screenshot of the actual finished layout (bottom right).  Layout concept (left), View hierarchy (right, top) and finished layout (right, bottom)

In the figure above:

  1. LinearLayout, the root ViewGroup, contains all the child View elements in a vertical orientation.
  2. Button (button_toast). The first child View element appears at the top in the LinearLayout.
  3. TextView (show_count). The second child View element appears under the first child View element in the LinearLayout.
  4. Button (button_count). The third child View element appears under the second child View element in the LinearLayout.

The layout hierarchy can grow to be complex for an app that shows many View elements on a screen. It's important to understand the hierarchy, as it affects whether View elements are visible and how efficiently they are drawn.

Tip: You can explore the layout hierarchy of your app using Hierarchy Viewer. It shows a tree view of the hierarchy and lets you analyze the performance of View elements on an Android-powered device. Performance issues are covered in a subsequent chapter.

The layout editor

You define layouts in the layout editor, or by entering XML code.

The layout editor shows a visual representation of XML code. You can drag View elements into the design or blueprint pane and arrange, resize, and specify attributes for them. You immediately see the effect of changes you make.

To use the layout editor, double-click the XML layout file (activity_main.xml). The layout editor appears with the Design tab at the bottom highlighted. (If the Text tab is highlighted and you see XML code, click the Design tab.) For the Empty Activity template, the layout is as shown in the figure below.  Exploring Android Studio

  1. XML layout file (activity_main.xml).
  2. Design and Text tabs. Click Design to see the layout editor, or Text to see XML code.
  3. Palette pane. The Palette pane provides a list of UI elements and layouts. Add an element or layout to the UI by dragging it into the design pane.
  4. Component Tree. The Component Tree pane shows the layout hierarchy. Click a View element or ViewGroup in this pane to select it. View elements are organized into a tree hierarchy of parents and children, in which a child inherits the attributes of its parent. In the figure above, the TextView is a child of the ConstraintLayout.
  5. Design and blueprint panes. Drag View elements from the Palette pane to the design or blueprint pane to position them in the layout. In the figure above, the layout shows only one element: a TextView that displays "Hello World".
  6. Attributes tab. Click Attributes to display the Attributes pane for setting attributes for a View element.

Layout editor toolbars

The layout editor toolbars provide buttons to configure your layout and change its appearance. The top toolbar lets you configure the appearance of the layout preview in the layout editor:  Top toolbar of the layout editor

The figure above shows the top toolbar of the layout editor:

  1. Select Design Surface: Select Design to display a color preview of the UI elements in your layout, or Blueprint to show only outlines of the elements. To see both panes side by side, select Design + Blueprint.
  2. Orientation in Editor: Select Portrait or Landscape to show the preview in a vertical or horizontal orientation. The orientation setting lets you preview the layout orientations without running the app on an emulator or device. To create alternative layouts, select Create Landscape Variation or other variations.
  3. Device in Editor: Select the device type (phone/tablet, Android TV, or Android Wear).
  4. API Version in Editor: Select the version of Android to use to show the preview.
  5. Theme in Editor: Select a theme (such as AppTheme) to apply to the preview.
  6. Locale in Editor: Select the language and locale for the preview. This list displays only the languages available in the string resources (see the lesson on localization for details on how to add languages). You can also select Preview as Right To Left to see the layout as if an RTL language had been chosen.

The layout editor also offers a second toolbar that lets you configure the appearance of UI elements in a ConstraintLayout and zoom in and out of the preview:  ConstraintLayout editing toolbar

The figure above shows the ConstraintLayout editing toolbar:

  1. Show: Select Show Constraints and Show Margins to show them in the preview, or to stop showing them.
  2. Autoconnect: Enable or disable Autoconnect. With Autoconnect enabled, you can drag any element (such as a Button) to any part of a layout to generate constraints against the parent layout.
  3. Clear All Constraints: Clear all constraints in the entire layout.
  4. Infer Constraints: Create constraints by inference.
  5. Default Margins: Set the default margins.
  6. Pack: Pack or expand the selected elements.
  7. Align: Align the selected elements.
  8. Guidelines: Add vertical or horizontal guidelines.
  9. Zoom controls: Zoom in or out.

Using ConstraintLayout

The layout editor offers more features in the Design tab when you use a ConstraintLayout, including handles for defining constraints.

A constraint is a connection or alignment to another UI element, to the parent layout, or to an invisible guideline. Each constraint appears as a line extending from a circular handle. After you select a UI element in the Component Tree pane or click it in the layout editor, the element shows a resizing handle on each corner and a circular constraint handle in the middle of each side.  The constraint and resizing handles on Views

The figure above shows the constraint and resizing handles on View elements in a layout:

  1. Resizing handle.
  2. Constraint line and handle. In the figure, the constraint aligns the left side of the Toast Button to the left side of the layout.
  3. Constraint handle without a constraint line.
  4. Baseline handle. The baseline handle aligns the text baseline of an element to the text baseline of another element.

In the blueprint or design panes, the following handles appear on the TextView element:

  • Constraint handle: To create a constraint, click a constraint handle, shown as a circle on each side of an element. Then drag the circle to another constraint handle or to a parent boundary. A zigzag line represents the constraint.  Constraint handle

  • Resizing handle: You can drag the square resizing handles to resize the element. While dragging, the handle changes to an angled corner.  Constraint handle

You can drag the resizing handles on each corner of the UI element to resize it, but doing so hard-codes the width and height dimensions, which you should avoid for most elements because hard-coded dimensions don't adapt to different screen densities.

Constraining a UI element

To add a constraint to a UI element, click the circular handle and drag a line to another element or to the side of a layout, as shown in the two animated figures below. To remove a constraint from an element, click the circular handle.  Deleting and adding a constraint

The constraints you define in the layout editor are created as XML attributes, which you can see in the Text tab as described in "Editing XML directly" in this chapter. For example, the following XML code is created constraining the top of an element to the top of its parent:


Using a baseline constraint

You can align one UI element that contains text, such as a TextView or Button, with another UI element that contains text. A baseline constraint lets you constrain the elements so that the text baselines match. Select the UI element that has text, and then hover your pointer over the element until the baseline constraint button appears underneath the element.

Click the baseline constraint button. The baseline handle appears, blinking in green as shown in the animated figure. Drag a baseline constraint line to the baseline of the other UI element.

Tip: For an in-depth tutorial on using ConstraintLayout, see Using ConstraintLayout to design your views.

Using the Attributes pane

The Attributes pane offers access to all of the XML attributes you can assign to a UI element. You can find the attributes (known as properties) common to all views in the View class documentation.

To show the Attributes pane, click the Attributes tab on the right side of the layout editor. The Attributes pane includes a square sizing panel called the view inspector. The symbols inside the view inspector represent the height and width settings.  Sizing panel in the Attributes pane

The figure above shows the Attributes pane:

  1. Vertical view size control. The vertical size control, which appears on the top and bottom of the view inspector, specifies the layout_height property. The angles indicate that this size control is set to wrap_content, which means the UI element expands vertically as needed to fit its contents. The "8" indicates a standard margin set to 8 dp.
  2. Horizontal view size control. The horizontal size control, which appears on the left and right of the view inspector, specifies the layout_width. The angles indicate that this size control is set to wrap_content, which means the UI element expands horizontally as needed to fit its contents, up to a margin of 8 dp.
  3. Attributes pane close button. Click to close the pane.

The layout_width and layout_height attributes in the Attributes pane change as you change the inspector's horizontal and vertical size controls. These attributes can take one of three values for a ConstraintLayout:

  • The match_constraint setting expands the UI element to fill its parent by width or height up to a margin, if a margin is set. The parent in this case is the ConstraintLayout.
  • The wrap_content setting shrinks the UI element to the size of its content. If there is no content, the element becomes invisible.
  • To specify a fixed size that's adjusted for the screen size of the device, set a number of dp (density-independent pixels). For example, 16dp means 16 density-independent pixels.

Tip: If you change the layout_width attribute using its popup menu, the layout_width attribute is set to zero because there is no set dimension. This setting is the same as match_constraint—the UI element can expand as much as possible to meet constraints and margin settings.

The Attributes pane offers access to all of the attributes you can assign to a View element. You can enter values for each attribute, such as the android:id, background, textColor, and text attributes.

Creating layout variants for orientations and devices

You can preview an app's layout with a horizontal orientation, and with different devices, without having to run the app on an emulator or device.

To preview the layout for a different orientation, click the Orientation in Editor button  Orientation in Editor button in the top toolbar. To show the layout in a horizontal orientation, select Switch to Landscape. To return to vertical orientation, select Switch to Portrait.

You can also preview the layout for different devices. Click the Device in Editor button  Device in Editor button in the top toolbar, and select a different device in the drop-down menu. For example, select Nexus 4, Nexus 5, and then Pixel to see differences in the previews.

To create a variant of the layout strictly for the horizontal orientation, leaving the vertical orientation layout alone: click the Orientation in Editor button and select Create Landscape Variation. A new editor window opens with the land/activity_main.xml tab showing the layout for the landscape (horizontal) orientation. You can change this layout, which is specifically for horizontal orientation, without changing the original portrait (vertical) orientation.

In the Project > Android pane, look inside the res > layout directory. You see that Android Studio automatically creates the variant for you, called activity_main.xml (land).  The file for the layout variant in the layout directory

To create a layout variant for tablet-sized screens, click the Orientation in Editor button and select Create layout x-large Variation. A new editor window opens with the xlarge/activity_main.xml tab showing the layout for a tablet-sized device. The editor also picks a tablet device, such as the Nexus 9 or Nexus 10, for the preview. In the Project > Android pane, look inside the res > layout directory. You see that Android Studio automatically creates the variant for you, called activity_main.xml (xlarge). You can change this layout, which is specifically for tablets, without changing the other layouts.

Editing XML directly

It is sometimes quicker and easier to edit the XML code directly, especially when copying and pasting the code for similar views.

To view and edit the XML code, open the XML layout file. The layout editor appears with the Design tab at the bottom highlighted. Click the Text tab to see the XML code. The following shows the XML code for a LinearLayout with two Button elements with a TextView in the middle:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:textColor="@android:color/white" />


        android:textColor="@android:color/white" />

XML attributes (view properties)

Views have properties that define where a view appears on the screen, its size, how the view relates to other views, and how it responds to user input. When defining views in XML or in the layout editor's Attributes pane, the properties are referred to as attributes.

For example, in the following XML description of a TextView, the android:id, android:layout_width, android:layout_height, android:background, are XML attributes that are translated automatically into the TextView properties:

       android:text="@string/count_initial_value" />

Attributes generally take this form:


The attribute_name is the name of the attribute. The value is a string with the value for the attribute. For example:


If the value is a resource, such as a color, the @ symbol specifies what kind of resource. For example:


The background attribute is set to the color resource identified as myBackgroundColor, which is declared to be #FFF043. Color resources are described in Style-related attributes in this chapter.

Every View and ViewGroup supports its own variety of XML attributes:

  • Some attributes are specific to a View subclass. For example, the TextView subclass supports the textSize attribute. Any elements that extend the TextView subclass inherit these subclass-specific attributes.
  • Some attributes are common to all View elements, because they are inherited from the root View class. The android:id attribute is one example.

For descriptions of specific attributes, see the overview section of the View class documentation.

Identifying a View

To uniquely identify a View and reference it from your code, you must give it an id. The android:id attribute lets you specify a unique id—a resource identifier for a View.

For example:


The @+id/button_count part of the attribute creates an id called button_count for a Button (a subclass of View). You use the plus (+) symbol to indicate that you are creating a new id.

Referencing a View

To refer to an existing resource identifier, omit the plus (+) symbol. For example, to refer to a View by its id in another attribute, such as android:layout_toLeftOf (described in the next section) to control the position of a View, you would use:


In the attribute above, @id/show_count refers to the View with the resource identifier show_count. The attribute positions the element to be "to the left of" the show_count View.

Positioning a View

Some layout-related positioning attributes are required for a View or a ViewGroup, and automatically appear when you add the View or ViewGroup to the XML layout.

LinearLayout positioning

LinearLayout is required to have these attributes set:

The android:layout_width and android:layout_height attributes can take one of three values:

  • match_parent expands the UI element to fill its parent by width or height. When the LinearLayout is the root ViewGroup, it expands to the size of the device screen. For a UI element within a root ViewGroup, it expands to the size of the parent ViewGroup.
  • wrap_content shrinks the UI element to the size of its content. If there is no content, the element becomes invisible.
  • Use a fixed number of dp (density-independent pixels) to specify a fixed size, adjusted for the screen size of the device. For example, 16dp means 16 density-independent pixels. Density-independent pixels and other dimensions are described in "Dimensions" in this chapter.

The android:orientation can be:

  • horizontal: Views are arranged from left to right.
  • vertical: Views are arranged from top to bottom.

Other layout-related attributes include:

  • android:layout_gravity: This attribute is used with a UI element to control where the element is arranged within its parent. For example, the following attribute centers the UI element horizontally within the parent ViewGroup:
  • Padding is the space, measured in density-independent pixels, between the edges of the UI element and the element's content, as shown in the figure below.  Padding

In the figure above: (1) Padding is the space between the edges of the TextView (dashed lines) and the content of the TextView (solid line). Padding is not the same as margin, which is the space from the edge of the View to its parent.

The size of a View includes its padding. The following are commonly used padding attributes:

  • android:padding: Sets the padding of all four edges.
  • android:paddingTop: Sets the padding of the top edge.
  • android:paddingBottom: Sets the padding of the bottom edge.
  • android:paddingLeft: Sets the padding of the left edge.
  • android:paddingRight: Sets the padding of the right edge.
  • android:paddingStart: Sets the padding of the start of the view, in pixels. Used in place of the padding attributes listed above, especially with views that are long and narrow.
  • android:paddingEnd: Sets the padding of the end edge of the view, in pixels. Used along with android:paddingStart.

Tip: To see all of the XML attributes for a LinearLayout, see the Summary section of the LinearLayout class definition. Other root layouts, such as RelativeLayout and AbsoluteLayout, also list their XML attributes in the Summary sections.

RelativeLayout Positioning

Another useful Viewgroup for layout is RelativeLayout, which you can use to position child View elements relative to each other or to the parent. The attributes you can use with RelativeLayout include the following:

For a complete list of attributes for View and View subclass elements in a RelativeLayout, see RelativeLayout.LayoutParams.

You specify style attributes to customize the appearance of a View. A View that doesn't have style attributes, such as android:textColor, android:textSize, and android:background, takes on the styles defined in the app's theme.

The following are style-related attributes used in lesson on using the layout editor:

  • android:background: Specifies a color or drawable resource to use as the background.
  • android:text: Specifies text to display in the view.
  • android:textColor: Specifies the text color.
  • android:textSize: Specifies the text size.
  • android:textStyle: Specifies the text style, such as bold.

Resource files

Resource files are a way of separating static values from code so that you don't have to change the code itself to change the values. You can store all the strings, layouts, dimensions, colors, styles, and menu text separately in resource files.

Resource files are stored in folders located in the res folder when viewing the Project > Android pane. These folders include:

  • drawable: For images and icons
  • layout: For layout resource files
  • menu: For menu items
  • mipmap: For pre-calculated, optimized collections of app icons used by the Launcher
  • values: For colors, dimensions, strings, and styles (theme attributes)

The syntax to reference a resource in an XML layout is as follows:


  • package_name is the name of the package in which the resource is located. The package name is not required when you reference resources that are stored in the res folder of your project, because these resources are from the same package.
  • resource_type is the R subclass for the resource type. See Resource Types for more about the resource types and how to reference them.
  • resource_name is either the resource filename without the extension, or the android:name attribute value in the XML element.

For example, the following XML layout statement sets the android:text attribute to a string resource:

  • No package_name is included, because the resource is stored in the strings.xml file in the project.
  • The resource_type is string.
  • The resource_name is button_label_toast.

Another example: this XML layout statement sets the android:background attribute to a color resource, and since the resource is defined in the project (in the colors.xml file), the package_name is not specified:


In the following example, the XML layout statement sets the android:textColor attribute to a color resource. However, the resource is not defined in the project but supplied by Android, so you need to specify the package_name, which is android, followed by a colon:


Tip: For more about accessing resources from code, see Accessing Resources. For Android color constants, see the Android standard R.color resources.

Values resource files

Keeping values such as strings and colors in separate resource files makes it easier to manage them, especially if you use them more than once in your layouts.

For example, it is essential to keep strings in a separate resource file for translating and localizing your app, so that you can create a string resource file for each language without changing your code. Resource files for images, colors, dimensions, and other attributes are handy for developing an app for different device screen sizes and orientations.


String resources are located in the strings.xml file (inside res > values in the Project > Android pane). You can edit this file directly by opening it in the editor pane:

    <string name="app_name">Hello Toast</string>
    <string name="button_label_count">Count</string>
    <string name="button_label_toast">Toast</string>
    <string name="count_initial_value">0</string>

The name (for example, button_label_count) is the resource name you use in your XML code, as in the following attribute:


The string value of this name is the word (Count) enclosed within the <string></string> tags. (You don't use quotation marks unless the quotation marks are part of the string value.)

Extracting strings to resources

You should also extract hard-coded strings in an XML layout file to string resources.  Extracting a string resource

 Naming the string resource

To extract a hard-coded string in an XML layout, follow these steps, as shown in the figure above:

  1. Click the hard-coded string and press Alt-Enter in Windows, or Option-Return in Mac OS X.
  2. Select Extract string resource.
  3. Edit the Resource name for the string value.

You can then use the resource name in your XML code. Use the expression "@string/resource_name" (including quotation marks) to refer to the string resource:



Color resources are located in the colors.xml file (inside res > values in the Project > Android pane). You can edit this file directly in the editor pane:

    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="myBackgroundColor">#FFF043</color>

The name (for example, colorPrimary) is the resource name you use in your XML code:


The color value of this name is the hexadecimal color value (#3F51B5) enclosed within the <color></color> tags. The hexadecimal value specifies red, green, and blue (RGB) values. The value always begins with a pound (#) character, followed by the Alpha-Red-Green-Blue information. For example, the hexadecimal value for black is #000000, while the hexadecimal value for a variant of sky blue is #559fe3. Base color values are listed in the Color class documentation.

The colorPrimary color is one of the predefined base colors and is used for the app bar. In a production app, you could, for example, customize this to fit your brand. Using the base colors for other UI elements creates a uniform UI.

Tip: For the Material Design specification for Android colors, see Style and Using the Material Theme. For common color hexadecimal values, see Color Hex Color Codes. For Android color constants, see the Android standard R.color resources.

You can see a small block of the color choice in the left margin next to the color resource declaration in colors.xml, and also in the left margin next to the attribute that uses the resource name in the layout XML file.  Color blocks in the resource file

 Color block in the layout file

Tip: To see the color in a popup, turn on the Autopopup documentation feature. Select Preferences > Editor > General > Code Completion, and select the "Autopopup documentation in (ms)" option. You can then hover your cursor over a color resource name to see the color.


To make dimensions easier to manage, you should separate the dimensions from your code, especially if you need to adjust your layout for devices with different screen densities. Keeping dimensions separate from code also makes it easy to have consistent sizing for UI elements, and to change the size of multiple elements by changing one dimension resource.

Dimension resources are located in the dimens.xml file (inside res > values in the Project > Android pane). The dimens.xml file can actually be a folder holding more than one dimens.xml file—one for each device screen resolution. You can edit each dimens.xml file directly:

    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="my_view_width">300dp</dimen>
    <dimen name="count_text_size">200sp</dimen>
    <dimen name="counter_height">300dp</dimen>

The name (for example, activity_horizontal_margin) is the resource name you use in the XML code:


The value of this name is the measurement (16dp) enclosed within the <dimen></dimen> tags.

You can extract dimensions in the same way as strings:

  1. Click the hard-coded dimension, and press Alt-Enter in Windows, or press Option-Return in Mac OS X.
  2. Select Extract dimension resource.
  3. Edit the Resource name for the dimension value.

Density-independent pixels (dp) are independent of screen resolution. For example, 10px (10 fixed pixels) look a lot smaller on a higher resolution screen, but Android scales 10dp (10 device-independent pixels) to look right on different resolution screens. Text sizes can also be set to look right on different resolution screens using scaled-pixel (sp) sizes.

Tip: For more information about dp and sp units, see Supporting Different Densities.


A style is a resource that specifies common attributes such as height, padding, font color, font size, background color. Styles are meant for attributes that modify the look of the view.

Styles are defined in the styles.xml file (inside res > values in the Project > Android pane). You can edit this file directly. Styles are covered in a later chapter, along with the Material Design Specification.

Other resource files

Android Studio defines other resources that are covered in other chapters:

  • Images and icons: The drawable folder provides icon and image resources. If your app does not have a drawable folder, you can manually create it inside the res folder. For more information about drawable resources, see Drawable Resources in the App Resources section of the Android Developer's Guide.
  • Optimized icons: The mipmap folder typically contains pre-calculated, optimized collections of app icons used by the Launcher. Expand the folder to see that versions of icons are stored as resources for different screen densities.
  • Menus: You can use an XML resource file to define menu items and store them in your project in the menu folder. Menus are described in a later chapter.

Responding to View clicks

A click event occurs when the user taps or clicks a clickable View, such as a Button, ImageButton, ImageView, or FloatingActionButton. When such an event occurs, your code performs an action. In order to make this pattern work, you have to:

  • Write a Java method that performs the specific action you want the app to do when this event occurs. This method is typically referred to as an event handler.
  • Associate this event-handler method to the View, so that the method executes when the event occurs.

The onClick attribute

Android Studio provides a shortcut for setting up a clickable View, and for associating an event handler with the View: use the android:onClick attribute in the XML layout.

For example, the following XML attribute sets a Button to be clickable, and sets showToast() as the event handler:


When the user taps the button_toast Button, the button's android:onClick attribute calls the showToast() method. In order to work with the android:onClick attribute, the showToast() method must be public and return void. To know which View called the method, the showToast() method must require a view parameter.

Android Studio provides a shortcut for creating an event handler stub (a placeholder for a method that you can fill in later) in the code for the Activity associated with the XML layout. Follow these steps:

  1. Inside the XML layout file (such as activity_main.xml), click the method name in the android:onClick attribute statement (showToast in the XML snippet above).
  2. Press Alt-Enter in Windows or Option-Return in Mac OS X, and select Create onClick event handler.
  3. Select the Activity associated with the layout file (such as MainActivity) and click OK. Android Studio creates a placeholder method stub in MainActivity.java as shown below.
public void showToast(View view) {
        // Do something in response to the button click.

Updating a View

To update a View, for example to replace the text in a TextView, your code must first instantiate an object from the View. Your code can then update the object, which updates the screen.

To refer to the View in your code, use the findViewById() method of the View class, which looks for a View based on the resource id. For example, the following statement sets mShowCount to be the TextView in the layout with the resource id show_count:

mShowCount = (TextView) findViewById(R.id.show_count);

From this point on, your code can use mShowCount to represent the TextView, so that when you update mShowCount, the TextView is updated.

For example, when the following Button with the android:onClick attribute is tapped, onClick calls the countUp() method:


You can implement countUp() to increment the count, convert the count to a string, and set the string as the text for the mShowCount object:

public void countUp(View view) {
        if (mShowCount != null)

Since you had already associated mShowCount with the TextView for displaying the count, the mShowCount.setText() method updates the TextView on the screen.

The related practical lessons are:

Learn more

Android Studio documentation:

Android developer documentation:

Material Design:


results matching ""

    No results matching ""