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.
Views
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:
-
for displaying text to enable the user to enter and edit text and other clickable elements (such as RadioButton , CheckBox , and Spinner ) to provide interactive behavior and RecyclerView to display scrollable items for displaying images and LinearLayout for containing other views and positioning them
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:
-
: A group that places UI elements (child View elements) using constraint connections to other elements and to the layout edges (parent View ). : A group that contains one other child View element and enables scrolling the child View element. : 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.
In the figure above:
- The root ViewGroup .
- 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:

-
: 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. : A group of child View elements positioned and aligned horizontally or vertically. : 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 . : A group of child View elements arranged into rows and columns. : 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. : A group that places its child View elements in a rectangular grid that can be scrolled.
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).
In the figure above:
- LinearLayout , the root ViewGroup , contains all the child View elements in a vertical orientation.
- Button ( button_toast ). The first child View element appears at the top in the LinearLayout .
- TextView ( show_count ). The second child View element appears under the first child View element in the LinearLayout .
- 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.
- XML layout file (activity_main.xml).
- Design and Text tabs. Click Design to see the layout editor, or Text to see XML code.
- 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.
- 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 .
- 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".
- 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:
The figure above shows the top toolbar of the layout editor:
- 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.
- 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.
- Device in Editor: Select the device type (phone/tablet, Android TV, or Android Wear).
- API Version in Editor: Select the version of Android to use to show the preview.
- Theme in Editor: Select a theme (such as AppTheme) to apply to the preview.
- 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:
The figure above shows the ConstraintLayout editing toolbar:
- Show: Select Show Constraints and Show Margins to show them in the preview, or to stop showing them.
- 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.
- Clear All Constraints: Clear all constraints in the entire layout.
- Infer Constraints: Create constraints by inference.
- Default Margins: Set the default margins.
- Pack: Pack or expand the selected elements.
- Align: Align the selected elements.
- Guidelines: Add vertical or horizontal guidelines.
- 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 figure above shows the constraint and resizing handles on View elements in a layout:
- Resizing handle.
- Constraint line and handle. In the figure, the constraint aligns the left side of the Toast Button to the left side of the layout.
- Constraint handle without a constraint line.
- 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.

Resizing handle: You can drag the square resizing handles to resize the element. While dragging, the handle changes to an angled corner.
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.
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.
The figure above shows the Attributes pane:
- 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.
- 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.
- 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 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 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) .
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:
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:
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 .
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.
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:
-
: Positions the right edge of this View to the left of another View (identified by its ID ). : Positions the left edge of this View to the right of another View (identified by its ID ). : Centers this View horizontally within its parent. : Centers this View vertically within its parent. : Positions the top edge of this View to match the top edge of the parent. : Positions the bottom edge of this View to match the bottom edge of the parent.
For a complete list of attributes for View and View subclass elements in a RelativeLayout , see RelativeLayout.LayoutParams .
Style-related attributes
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 : resource_type / resource_name
- 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.
Strings
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:
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.

To extract a hard-coded string in an XML layout, follow these steps, as shown in the figure above:
- Click the hard-coded string and press Alt-Enter in Windows, or Option-Return in Mac OS X.
- Select Extract string resource.
- 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:
Colors
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:
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.

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.
Dimensions
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:
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:
- Click the hard-coded dimension, and press Alt-Enter in Windows, or press Option-Return in Mac OS X.
- Select Extract dimension resource.
- 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 1 0dp (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.
Styles
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:
- 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).
- Press Alt-Enter in Windows or Option-Return in Mac OS X, and select Create onClick event handler.
- 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.
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 :
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:
Поддержка разных размеров экрана при разработке android приложений
В этом уроке рассказывается, как создать макет, который адаптируется к разным размерам экрана, используя масштабируемые представления, объекты RelativeLayout , квалификаторы размера и ориентации, фильтры псевдонимов и растровые изображений формата nine-patch.
Код, приведенный в уроке, взят из учебного приложения, в котором демонстрируются способы оптимизации для разных экранов. Вы можете загрузить его здесь и использовать части кода в собственном приложении.
В этом уроке описаны следующие аспекты обеспечения совместимости интерфейса с разными экранами:
- обеспечение способности макета адаптироваться к размеру экрана;
- выбор макета интерфейса, отвечающего конфигурации экрана;
- контроль правильности применяемого макета;
- использование масштабируемых растровых изображений.
Использование параметров wrap_content и match_parent
Чтобы создать масштабируемый макет, способный адаптироваться к разным экранам, используйте в качестве значений ширины и высоты отдельных компонентов представления параметры «wrap_content» и «match_parent» . Если используется «wrap_content» , для ширины или высоты представления устанавливается минимальное значение, позволяющее уместить содержание на экран, а параметр «match_parent» (известный как «fill_parent» в API до 8 уровня) служит для растягивания компонента по размеру родительского представления.
Если указать параметры «wrap_content» и «match_parent» вместо строго заданных размеров, в представлениях будет использоваться минимально необходимое место или они будут растягиваться на всю доступную длину и ширину соответственно. Например:
Обратите внимание на то, что в коде учебного приложения размеры компонентов заданы с помощью параметров «wrap_content» и «match_parent» . В результате макет правильно отображается на экранах разных размеров при разных ориентациях.
Например, вот так он выглядит в вертикальной и горизонтальной ориентациях. Обратите внимание на то, как размеры компонентов автоматически адаптируются к длине и ширине:

Рисунок 1. Приложение News Reader при вертикальной (слева) и горизонтальной (справа) ориентации.
Использование объекта RelativeLayout
С помощью вложенных экземпляров объекта LinearLayout и параметров «wrap_content» и «match_parent» можно создавать достаточно сложные макеты. Однако LinearLayout не дает возможности точно управлять взаимным расположением дочерних представлений: в LinearLayout они просто помещаются в ряд друг за другом. Если необходимо расположить дочерние представления иным образом, используйте объект RelativeLayout , позволяющий задать относительные позиции компонентов. Например, одно дочернее представление можно выровнять по левому краю экрана, а другое – по правому.
На рис. 2 показано, как этот макет выглядит на экране QVGA.

Рисунок 2. Скриншот экрана QVGA (маленького размера).
На рис. 3 показано, как он выглядит на экране с большей диагональю.

Рисунок 3. Скриншот экрана WSVGA (большего размера).
Обратите внимание: несмотря на изменение размера компонентов их взаимное расположение остается прежним, так как оно задано объектом RelativeLayout.LayoutParams .
Использование квалификаторов размера
Масштабируемые или относительные макеты, один из которых продемонстрирован выше, имеют свои ограничения. Хотя они позволяют создать интерфейс, способный адаптироваться к разным экранам за счет растягивания пространства внутри и вокруг компонентов, пользователю может оказаться не слишком удобно работать с таким интерфейсом. Поэтому в приложении должен использоваться не один масштабируемый макет, а несколько альтернативных вариантов для разных конфигураций экрана. Их можно создать с помощью квалификаторов конфигураций, которые позволяют оперативно выбирать ресурсы, отвечающие текущим параметрам экрана (например, разные варианты макетов для экранов разных размеров).
Многие приложения отображаются на больших экранах в двухпанельном режиме, при котором список элементов расположен в одной панели, а их содержание открывается в другой. Такой режим просмотра удобен на достаточно больших экранах планшетных ПК и телевизоров, однако на экране телефона эти панели следует отображать по отдельности. Для каждого режима просмотра нужно создать отдельный файл.
- res/layout/main.xml , однопанельный макет (по умолчанию):
- res/layout-large/main.xml , двухпанельный макет:
Обратите внимание, что во втором случае в названии каталога использован квалификатор large . Этот макет будет выбран на устройствах, экраны которых считаются большими (например, 7 дюймов и более). Первый макет (без квалификаторов) будет выбран для устройств с маленьким экраном.
Использование квалификатора Smallest-width
Одной из проблем, с которой сталкивались разработчики приложений для устройств Android версий до 3.2, было слишком общее определение “большого” экрана. Это касалось устройств Dell Streak, первой модели Galaxy Tab и планшетных ПК с экраном размером 7 дюймов. Многие приложения требовалось по-разному отображать на разных устройствах (например, с 5- и 7-дюймовыми экранами), хотя они и относились к одной категории “больших” экранов. В Android версии 3.2 и более поздних доступен квалификатор Smallest-width.
Он позволяет определять экраны с заданной минимальной шириной в dp. Например, типичный планшетный ПК с экраном 7 дюймов имеет минимальную ширину 600 dp, и если вы хотите, чтобы приложение работало на нем в двухпанельном режиме (а на меньших экранах в однопанельном), используйте два макета из предыдущего раздела, но вместо квалификатора размера large укажите sw600dp . В таком случае на экранах, минимальная ширина которых составляет 600 dp, будет использоваться двухпанельный макет.
- res/layout/main.xml , однопанельный макет (по умолчанию):
- res/layout-sw600dp/main.xml , двухпанельный макет:
Это означает, что на устройствах, минимальная ширина экрана которых не меньше 600 dp, будет выбран layout-sw600dp/main.xml (двухпанельный макет), а на экранах меньшего размера – layout/main.xml (однопанельный макет).
Следует учесть, что на Android-устройствах до версии 3.2 квалификатор sw600dp не будет работать, поэтому для них по-прежнему нужно использовать large . Таким образом, вам потребуется еще один файл с названием res/layout-large/main.xml , идентичный файлу res/layout-sw600dp/main.xml . В следующем разделе вы познакомитесь с методом, который позволяет избежать дублирования таких файлов макета.
Использование псевдонимов макетов
Квалификатор Smallest-width работает только на устройствах Android 3.2 или более поздних версий. Для совместимости с более ранними устройствами по-прежнему следует использовать абстрактные размеры (small, normal, large и xlarge). Например, чтобы интерфейс открывался в однопанельном режиме на телефонах и в многопанельном на планшетных ПК с 7-дюймовым экраном, телевизорах и других крупных устройствах, подготовьте следующие файлы:
- res/layout/main.xml: однопанельный макет;
- res/layout-large: многопанельный макет;
- res/layout-sw600dp: многопанельный макет.
Последние два файла идентичны: один из них предназначен для устройств Android 3.2 и новее, а второй для более старых планшетных ПК и телевизоров на платформе Android.
Чтобы не создавать дубликаты файлов и упростить процесс поддержки приложения, используйте псевдонимы. Например, можно определить следующие макеты:
- res/layout/main.xml (однопанельный макет);
- res/layout/main_twopanes.xml (двухпанельный макет).
Затем добавьте следующие два файла:
- res/values-large/layout.xml :
- res/values-sw600dp/layout.xml :
Содержание последних двух файлов одинаково, но сами по себе они не определяют макет. Они служат для того, чтобы назначить файл main в качестве псевдонима main_twopanes . Так как в них используются селекторы large и sw600dp , они применяются к планшетным ПК и телевизорам на платформе Android независимо от версии (для версий до 3.2 используется large , а для более новых – sw600dp ).
Использование квалификаторов ориентации
Хотя некоторые макеты одинаково хорошо смотрятся в вертикальной и горизонтальной ориентациях, в большинстве случаев интерфейс все же приходится адаптировать. Ниже показано, как изменяется макет в приложении News Reader в зависимости от размера и ориентации экрана.
- Маленький экран, вертикальная ориентация: однопанельный вид с логотипом.
- Маленький экран, горизонтальная ориентация: однопанельный вид с логотипом.
- Планшетный ПК с 7-дюймовым экраном, вертикальная ориентация: однопанельный вид с панелью действий.
- Планшетный ПК с 7-дюймовым экраном, горизонтальная ориентация: двухпанельный вид с панелью действий.
- Планшетный ПК с 10-дюймовым экраном, вертикальная ориентация: двухпанельный вид (узкий вариант) с панелью действий.
- Планшетный ПК с 10-дюймовым экраном, горизонтальная ориентация: двухпанельный вид (широкий вариант) с панелью действий.
- Телевизор, горизонтальная ориентация: двухпанельный вид с панелью действий.
Каждый из этих макетов определен в XML-файле в каталоге res/layout/ . Чтобы сопоставить их с определенными конфигурациями экрана, в приложении используются псевдонимы:
После того как все возможные макеты определены, остается сопоставить каждый из них с подходящей конфигурацией, используя квалификаторы конфигураций. Воспользуемся псевдонимами макетов:
Использование растровых изображений nine-patch
Чтобы интерфейс был совместим с экранами разных размеров, используемые в нем графические элементы также должны быть адаптированы соответствующим образом. Например, фон кнопки должен одинаково хорошо выглядеть независимо от ее формы.
Если использовать для компонентов, размеры которых меняются, обычные изображения, то они будут равномерно сжиматься и растягиваться, и результат будет далек от идеального. Решением являются растровые изображения формата nine-patch – специальные PNG-файлы, содержащие информацию о том, какие области можно растягивать, а какие нет.
Создавая растровые изображения для масштабируемых компонентов, обязательно используйте формат nine-patch. На рис. 4 показано обычное растровое изображение (увеличенное в 4 раза для наглядности), которое мы переведем в формат nine-patch.
Рисунок 4. button.png
Откройте его с помощью утилиты draw9patch , входящей в комплект разработчика (в каталоге tools/ ). Установите метки на левом и верхнем краях, чтобы ограничить области, которые можно растягивать. Можно также провести линию вдоль правого и нижнего краев, как показано на рис. 5, чтобы отметить области, в которых содержание должно быть зафиксировано.
Рисунок 5. button.9.png
Обратите внимание на черные пиксели по краям. Метки у верхней и левой границ обозначают те области, которые можно растягивать, а метки у правой и нижней границ – те, куда должно быть помещено содержание.
Также обратите внимание на расширение .9.png . Оно должно быть задано именно в таком виде, чтобы система могла определить, что это формат nine-patch, а не обычный PNG-файл.
При применении этого фона к компоненту (с помощью android:background=»@drawable/button» ) изображение будет растянуто по размеру кнопки, как показано на рис. 6.
Рисунок 6. Кнопки разных размеров с файлом фона button.9.png в формате nine-patch.
What's the difference between fill_parent and wrap_content?
In Android, when layout out widgets, what’s the difference between fill_parent ( match_parent in API Level 8 and higher) and wrap_content ?
Is there any documentation where you can point to? I’m interested in understanding it very well.
![]()
4 Answers 4
Either attribute can be applied to View’s (visual control) horizontal or vertical size. It’s used to set a View or Layouts size based on either it’s contents or the size of it’s parent layout rather than explicitly specifying a dimension.
fill_parent (deprecated and renamed MATCH_PARENT in API Level 8 and higher)
Setting the layout of a widget to fill_parent will force it to expand to take up as much space as is available within the layout element it’s been placed in. It’s roughly equivalent of setting the dockstyle of a Windows Form Control to Fill .
Setting a top level layout or control to fill_parent will force it to take up the whole screen.
wrap_content
Setting a View’s size to wrap_content will force it to expand only far enough to contain the values (or child controls) it contains. For controls — like text boxes (TextView) or images (ImageView) — this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It’s roughly the equivalent of setting a Windows Form Control’s Autosize property to True.
Name already in use
PiRIS / articles / android_studio.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
0 contributors
Users who have contributed to this file
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Первый проект в Android Studio
Создание первого приложения, структура проекта
Cоздадим первое приложение в среде Android Studio для операционной системы Android. Откроем Android Studio и на начальном экране выберем пункт New Project (либо, если какой-то проект уже открыт, через главное меню File — New Project)
При создании проекта Android Studio вначале предложит нам выбрать шаблон проекта:
Внешний вид может немного отличаться, т.к. я пишу лекции под Linux

Android Studio предоставляет ряд шаблонов для различных ситуаций. Выберем в этом списке шаблон Empty Activity, который предосавляет самый простейший фукционал, необходимый для начала, и нажмем на кнопку Next.
После этого отобразится окно настроек нового проекта:

В окне создания нового проекта мы можем установить его начальные настройки:
В поле Name вводится название приложения.
В поле Package Name указывается имя пакета, где будет размещаться главный класс приложения. В для тестовых проектов это значение не играет ольшого значения.
В поле Save Location установливается расположение файлов проекта на жестком диске. Можно оставить значение по умолчанию.
В поле Language указывается используемый язык программирования, по умолчанию в этом поле стоит Kotlin (поддерживается и Java).
В поле Minimum SDK указывается самая минимальная поддерживаемая версия SDK. Оставим значение по умолчанию — API 21: Android 5.0 (Lollipop), которая означает, что наше приложение можно будет запустить начиная с Android 5.0, а это 94% устройств. На более старых устройствах запустить будет нельзя.
Стоит учитывать, что чем выше версия SDK, тем меньше диапазон поддерживаемых устройств.
Далее нажмем на кнопку Finish, и Android Studio создаст новый проект (процесс создания достаточно долгий):

Вначале вкратце рассмотрим структуру проекта, что он уже имеет по умолчанию

Проект Android может состоять из различных модулей. По умолчанию, когда мы создаем проект, создается один модуль — app. Модуль имеет три подпапки:
manifests: хранит файл манифеста AndroidManifest.xml , который описывает конфигурацию приложения и определяет каждый из компонентов данного приложения.
java: хранит файлы кода (всегда называется Java, хотя мы и пишем на Kotlin), которые структурированы по отдельным пакетам. Так, в папке ru.yotc.myapplication (название которого было указано на этапе создания проекта) имеется по умолчанию файл MainActivity.kt с кодом на языке Kotlin, который представляет класс MainActivity, запускаемый по умолчанию при старте приложения
res: содержит используемые в приложении ресурсы. Все ресурсы разбиты на подпапки.
папка drawable предназначена для хранения изображений, используемых в приложении
папка layout предназначена для хранения файлов, определяющих графический интерфейс. По умолчанию здесь есть файл activity_main.xml , который определяет интерфейс для класса MainActivity в виде xml
папки mipmap содержат файлы изображений, которые предназначены для создания иконки приложения при различных разрешениях экрана.
папка values хранит различные xml-файлы, содержащие коллекции ресурсов — различных данных, которые применяются в приложении. По умолчанию здесь есть два файла и одна папка:
файл colors.xml хранит описание цветов, используемых в приложении
файл strings.xml содержит строковые ресурсы, используемые в приложении
папки themes хранит две темы приложения — для светлую (дневную) и темную (ночную)
Отдельный элемент Gradle Scripts содержит ряд скриптов, которые используются при построении приложения.
Во всей этой структуре следует выделить файл MainActivity.kt, который открыт в Android Studio и который содержит логику приложения и собственно с него начинается выполнение приложения. И также выделим файл activity_main.xml, который определяет графический интерфейс — по сути то, что увидит пользователь на своем устройстве после загрузки приложения.
Созданный выше проект уже содержит некоторый примитивный функционал. Правда, этот функционал почти ничего не делает, только выводит на экран строку «Hello world!». Тем не менее это уже фактически приложение, которое мы можем запустить.
Для запуска и тестирования приложения мы можем использовать эмуляторы или реальные устройства. Но в идеале лучше тестировать на реальных устройствах. К тому же эмуляторы требуют больших аппаратных ресурсов, и не каждый компьютер может потянуть требования эмуляторов. А для использования мобильного устройства для тестирования может потребоваться разве что установить необходимый драйвер.
Запустим проект, нажав на зеленую стрелочку на панели инструментов.

И после запуска мы увидим наше приложение на экране, которое просто выводит на экран строку Hello World.

Но почему у нас выводится именно эта строка? Почему у нас вообще создается именно такой визуальный интерфейс?
Выполнение приложения Android по умолчанию начинается с класса MainActivity, который по умолчанию открыт в Android Studio:
Каждый отдельный экран или страница в приложении описывается таким понятием как activity. В литературе могут использоваться различные термины: экран, страница, активность. В данном случае я буду использовать понятие «activity». Так вот, если мы запустим приложение, то на экране мы по сути увидим определенную activity, которая предсталяет данный интерфейс.
Класс MainActivity по сути представляет обычный класс, в начале которого идет определение пакета данного класса:
Далее идет импорт классов из других пакетов, функциональность которых используется в MainActivity:
По умолчанию MainActivity наследуется от класса AppCompatActivity, который выше подключен с помощью директивы импорта. Класс AppCompatActivity по сути представляет отдельный экран (страницу) приложения или его визуальный интерфейс. И MainActivity наследует весь этот функционал.
По умолчанию MainActivity содержит только один метод onCreate(), в котором фактически и создается весь интерфейс приложения:
В метод setContentView() передается ресурс разметки графического интерфейса:
Именно здесь и решается, какой именно визуальный интерфейс будет иметь MainActivity. Но что в данном случае представляет ресурс R.layout.activity_main? Это файл activity_main.xml из папки res/layout (в принципе можно заметить, что название ресурса соответствует названию файла), который также по умолчанию открыт в Android Studio:

Android Studio позволяет работать с визуальным интерфейсом как в режиме кода, так и в графическом режиме. Так, по умолчанию файл открыт в графическом режиме, и мы наглядно можем увидеть, как у нас примерно будет выглядеть экран приложения. И даже набросать с панели инструментов какие-нибудь элементы управления, например, кнопки или текстовые поля.
Но также мы можем работать с файлом в режиме кода, поскольку activity_main.xml — это обычный текстовый файл с разметкой xml. Для переключения к коду нажмём на кнопку Code над графическим представлением. (Дополнительно с помощью кнопки Split можно переключиться на комбинированное представление код + графический дизайнер)
Здесь мы увидим, что на уровне кода файл activity_main.xml содержит следующую разметку:
Весь интерфейс представлен элементом-контейнером androidx.constraintlayout.widget.ConstraintLayout. ConstraintLayout позволяет расположить вложенные элементы в определенных местах экрана.
Атрибут android:layout_width определяет ширину контейнера.
Значением атрибута android:layout_width является «match_parent». Это значит, что элемент (ConstraintLayout) будет растягиваться по всей ширине контейнера (экрана устройства).
Атрибут android:layout_height=»match_parent» определяет высоту контейнера. Значение «match_parent» указывает, что ConstraintLayout будет растягивается по всей высоте контейнера (экрана устройства).
Атрибут tools:context определяет, какой класс activity (экрана приложения) связан с текущим определением интерфейса. В данном случае это класс MainActivity. Это позволяет использовать в Android Studio различные возможности в режиме дизайнера, которые зависят от класса activity.
Внутри контейнера ConstraintLayout расположен текстовый блок:
TextView
android:layout_width устанавливает ширину виджета. Значение wrap_content задает для виджета величину, достаточную для отображения в контейнере.
android:layout_height устанавливает высоту виджета. Значение wrap_content аналогично установке ширины задает для виджета высоту, достаточную для отображения в контейнере
android:text устанавливает текст, который будет выводиться в TextView (в данном случае это строка «Hello World!»)
app:layout_constraintLeft_toLeftOf=»parent»: указывает, что левая граница элемента будет выравниваться по левой стороне контейнера ConstraintLayout
app:layout_constraintTop_toTopOf=»parent»: указывает, что верхняя граница элемента будет выравниваться по верхней стороне контейнера ConstraintLayout
app:layout_constraintRight_toRightOf=»parent»: указывает, что правая граница элемента будет выравниваться по правой стороне контейнера ConstraintLayout
app:layout_constraintBottom_toBottomOf=»parent»: указывает, что нижняя граница элемента будет выравниваться по нижней стороне контейнера ConstraintLayout
Стоит отметить, что последние четыре атрибута вместе будут приводить к расположению TextView по центру экрана.
Таким образом, при запуске приложения сначала запускается класс MainActivity, который в качестве графического интерфейса устанавливает разметку из файла activity_main.xml . И поскольку в этой разметке прописан элемент TextView, который представляет некоторый текст, то мы и увидим его текст на экране.
Определение интерфейса в файле XML. Файлы layout
Как правило, для определения визуального интерфейса в проектах под Android используются специальные файлы xml. Эти файлы являются ресурсами разметки и хранят определение визуального интерфейса в виде кода XML. Подобный подход напоминает создание веб-сайтов, когда интерфейс определяется в файлах html, а логика приложения — в коде javascript.
Объявление пользовательского интерфейса в файлах XML позволяет отделить интерфейс приложения от кода. Что означает, что мы можем изменять определение интерфейса без изменения кода. Например, в приложении могут быть определены разметки в файлах XML для различных ориентаций монитора, различных размеров устройств, различных языков и т.д. Кроме того, объявление разметки в XML позволяет легче визуализировать структуру интерфейса и облегчает отладку.
Файлы разметки графического интерфейса располагаются в проекте в каталоге res/layout . По умолчанию при создании проекта с пустой activity уже есть один файл ресурсов разметки activity_main.xml
В файле определяются все графические элементы и их атрибуты, которые составляют интерфейс. При создании разметки в XML следует соблюдать некоторые правила: каждый файл разметки должен содержать один корневой элемент, который должен представлять объект View или ViewGroup.
В нашем случае корневым элементом является элемент ConstraintLayout, который содержит элемент TextView.
При компиляции каждый XML-файл разметки компилируется в ресурс View. Загрузка ресурса разметки осуществляется в методе Activity.onCreate. Чтобы установить разметку для текущего объекта activity, надо в метод setContentView() в качестве параметра передать ссылку на ресурс разметки.
Для получения ссылки на ресурс в коде необходимо использовать выражение R.layout.[название_ресурса] . Название ресурса layout будет совпадать с именем файла.
Но у нас может быть и несколько различных ресурсов layout. Как правило, каждый отдельный класс Activity использует свой файл layout. Либо для одного класса Activity может использоваться сразу несколько различных файлов layout.
Добавление файла layout
К примеру, добавим в проект новый файл разметки интерфейса. Для этого нажмем на папку res/layout правой кнопкой мыши и в появившемся меню выберем пункт New -> Layout Resource File
После этого в специальном окошке будет предложено указать имя и корневой элемент для файла layout:

В качестве названия укажем second_layout. Все остальные настройки оставим по умолчанию:
в поле Root element указывается корневой элемент. По умолчанию это androidx.constraintlayout.widget.ConstraintLayout.
поле Source set указывает, куда помещать новый файл. По умолчанию это main — область проекта, с которой мы собственно работаем при разаботке приложения.
поле Directory name указывает папку в рамках каталога, выбранного в предыдущей опции, в который собственно помещается новый файл. По умолчанию для файлов с разметкой интерфейса это layout.
После этого в папку res/layout будет добавлен новый файл second_layout.xml, с которым мы можем работать точно также, как и с activity_main.xml.
При создании он содержит только корневой элемент:
Добавим в него текстовое поле:
Здесь определено текстовое поле TextView, которое имеет следующие атрибуты:
android:id — идентификатор элемента, через который мы сможем ссылаться на него в коде. В записи android:id=»@+id/header» символ @ указывает XML-парсеру использовать оставшуюся часть строки атрибута как идентификатор. А знак + означает, что если для элемента не определен id со значением header, то его следует определить.
android:text — текст элемента — на экран будет выводиться строка «Welcome to Android».
android:textSize — высота шрифта (здесь 26 единиц)
android:layout_width — ширина элемента. Значение «match_parent» указывает, что элемент будет растягиваться по всей ширине контейнера ConstraintLayout
android:layout_height — высота элемента. Значение «match_parent» указывает, что элемент будет растягиваться по всей высоте контейнера ConstraintLayout
Применим этот файл в качестве определения графического интерфейса в классе MainActivity:
Файл интерфейса называется second_layout.xml , поэтому по умолчанию для него будет создаваться ресурс R.layout.second_layout. Соответственно, чтобы его использовать, мы передаем его в метода setContentView. В итоге мы увидим на экране следующее:

Получение и управлене визуальными элементами в коде
Выше определенный элемент TextView имеет один очень важный атрибут — id или идентификатор элемента. Этот идентификатор позволяет обращаться к элементу, который определен в файле xml, из кода. Например, перейдем к классу MainActivity и изменим его код:
Для получения элементов по id класс Activity имеет метод findViewById(). В этот метод передается идентификатор ресурса в виде R.id.[идентификатор_элемента] . Этот метод возвращает объект View — объект базового класса для всех элементов, поэтому результат метода еще необходимо привести к типу TextView.
Выше мы приводили тип указывая нужный в угорвых скобках метода, но можно явно определить тип переменной:
Далее мы можем что-то сделать с этим элементом, в данном случае изменяем его текст.
Причем что важно, получение элемента происходит после того, как в методе setContentView была установлена разметка, в которой этот визуальный элемент был определен.
И если мы запустим проект, то увидим, что TextView выводит новый текст:

При разработке приложений под Android мы можем использовать различные типы измерений:
px: пиксели текущего экрана. Однако эта единица измерения не рекомендуется, так как реальное представление внешнего вида может изменяться в зависимости от устройства; каждое устройство имеет определенный набор пикселей на дюйм, поэтому количество пикселей на экране может также меняться
dp: (device-independent pixels) независимые от плотности экрана пиксели. Абстрактная единица измерения, основанная на физической плотности экрана с разрешением 160 dpi (точек на дюйм). В этом случае 1dp = 1px. Если размер экрана больше или меньше, чем 160dpi, количество пикселей, которые применяются для отрисовки 1dp соответственно увеличивается или уменьшается. Например, на экране с 240 dpi 1dp=1,5px, а на экране с 320dpi 1dp=2px. Общая формула для получения количества физических пикселей из dp: px = dp * (dpi / 160)
sp: (scale-independent pixels) независимые от масштабирования пиксели. Допускают настройку размеров, производимую пользователем. Рекомендуются для работы со шрифтами.
pt: 1/72 дюйма, базируются на физических размерах экрана
Предпочтительными единицами для использования являются dp. Это связано с тем, что мир мобильных устройств на Android сильно фрагментирован в плане разрешения и размеров экрана.
Ширина и высота элементов
Все визуальные элеметы, которые мы используем в приложении, как правило, упорядочиваются на экране с помощью контейнеров. В Android подобными контейнерами служат такие классы как RelativeLayout, LinearLayout, GridLayout, TableLayout, ConstraintLayout, FrameLayout. Все они по разному располагают элементы и управляют ими, но есть некоторые общие моменты при компоновке визуальных компонентов, которые мы сейчас рассмотрим.
Для организации элементов внутри контейнера используются параметры разметки. Для их задания в файле xml используются атрибуты, которые начинаются с префикса layout_. В частности, к таким параметрам относятся атрибуты layout_height и layout_width, которые используются для установки размеров и могут использовать одну из следующих опций:
Растяжение по всей ширине или высоте контейнера с помощью значения match_parent (для всех контейнеров кроме ConstraintLayout) или 0dp (для ConstraintLayout)
Растяжение элемента до тех границ, которые достаточны, чтобы вместить все его содержимое с помощью значения wrap_content
Точные размеры элемента, например 96 dp
match_parent
Установка значения match_parent позволяет растянуть элемент по всей ширине или высоте контейнера. Стоит отметить, что данное значение применяется ко всем контейнерам, кроме ConstraintLayout. Например, рястянем элемент TextView по всей ширине и высоте контейнера LinearLayout:
Контейнер самого верхнего уровня, в качестве которого в данном случае выступает LinearLayout, для высоты и ширины имеет значение match_parent, то есть он будет заполнять всю область для activity — как правило, весь экран.
И TextView также принимает подобные атрибуты. Значение android:layout_width=»match_parent» обеспечивает растяжение по ширине, а android:layout_height=»match_parent» — по вертикали. Для наглядности в TextView применяет атрибут android:background, который задает фон элемента и в данном случае окрашивает фон в цвет «#e0e0e0», благодаря чему мы можем увидеть занимаемую им область.

wrap_content
Значение wrap_content устанавливает те значения для ширины или высоты, которые необходимы, чтобы разместить на экране содержимое элемента:

Внутренние и внешние отступы
Параметры разметки позволяют задать отступы как от внешних границ элемента до границ контейнера, так и внутри самого элемента между его границами и содержимым.
Padding
Для установки внутренних отступов применяется атрибут android:padding. Он устанавливает отступы контента от всех четырех сторон контейнера. Можно устанавливать отступы только от одной стороны контейнера, применяя следующие атрибуты: android:paddingLeft, android:paddingRight, android:paddingTop и android:paddingBottom.
Стоит отметить, что вместо атрибутов android:paddingLeft и android:paddingRight можно применять атрибуты android:paddingStart и android:paddingEnd, которые разработаны специально адаптации приложения для работы как для языков с левосторонней ориентацией, так и правосторонней ориентацией (арабский, фарси).
Margin
Для установки внешних отступов используется атрибут layout_margin. Данный атрибут имеет модификации, которые позволяют задать отступ только от одной стороны: android:layout_marginBottom, android:layout_marginTop, android:layout_marginLeft и android:layout_marginRight.