- Mastering Android Development with Kotlin
- Milo? Vasi?
- 1344字
- 2021-07-02 15:20:57
Android layouts
We will continue our work by defining layouts for each screen. Layouts in Android are defined in XML. We will mention the most commonly used layout types and populate them with commonly used layout components.
Each layout file has one of the layout types as its top-level container. Layouts can contain other layouts with UI components and so on. We can nest it. Let's mention the most commonly used layout types:
- Linear layout: This aligns UI components in a linear order, vertically or horizontally
- Relative layout: These UI components are aligned relatively to each other
- List view layout: All items are organized in the form of a list
- Grid view layout: All items are organized in the form of a grid
- Scroll view layout: This is used to enable scrolling when its content becomes higher than the actual height of the screen
Layout elements that we just mentioned are view groups. Each view group contains other views. View groups extend the ViewGroup class. At the top, everything is a View class. Classes (views) that are extending the View class, but do not extend ViewGroup, can't contain other elements (children). Such examples are Button, ImageButton, ImageView, and similar classes. Therefore, it's possible, for example, to define a RelativeLayout that contains a LinearLayout, which contains other multiple views aligned vertically or horizontally and so on.
We will now highlight some commonly used views:
- Button: This is a Base class that represents a button linked to the onClick action we define
- ImageButton: This is a button with an image used as its visual representation
- ImageView: This is a view that displays an image loaded from different sources
- TextView: This is a view that contains single or multiline non-editable text
- EditText: This is a view that contains single or multiline editable text
- WebView: This is a view that presents rendered HTML pages loaded from different sources
- CheckBox: This is a main two-states choice view
Every View and ViewGroup supports misc XML attributes. Some attributes are specific to only certain view types. There are also attributes that are the same for all views. We will highlight the most commonly used view attributes through the examples of our screens later in this chapter.
To assign a unique identifier by which you can access a view through the code or other layout members, you must define an ID. To assign an ID to a view, use the syntax like in this example:
android:id="@+id/my_button"
In this example, we assigned the my_button ID to a view. To access it from code, we will use the following:
R.id.my_button
R is a generated class providing us access to resources. To create an instance of the button, we will use the findViewById() method defined in the Android Activity class:
val x = findViewById(R.id.my_button) as Button
Since we used Kotlin, we can access it directly, as shown in this example:
my_button.setOnClickListener { ... }
The @ symbol at the beginning of the string indicates that the XML parser should parse and expand the rest of the ID string and identify it as an ID resource. The + symbol means that this is a new resource name. When referencing an Android resource ID, you do not need the + symbol, as shown in this example:
<ImageView android:id="@+id/flowers" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/my_button" />
Let's build our UI for the main application screen! We will start with some prerequisites. In the values resource directory, create dimens.xml to define some dimensions we will use:
<?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="button_margin">20dp</dimen> <dimen name="header_height">50dp</dimen> </resources>
Android defines dimensions in the following units:
- px (pixels): This corresponds to actual pixels on the screen
- in (inches): This is based on the physical size of the screen, that is, 1 inch = 2.54 centimeters
- mm (millimeters): This is based on the physical size of the screen
- pt (points): This is the 1/72 of an inch based on the physical size of the screen
And the most important for us is the following:
- dp (Density-independent Pixels): This represents an abstract unit that is based on the physical density of the screen. They are relative to a 160 DPI screen. One dp is one pixel on a 160 DPI screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion.
- sp (Scale-independent Pixels): These are like the dp unit and generally used for font size.
We have to define a header layout that will be included on all screens. Create the activity_header.xml file and define it like this:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=
"http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/header_height"> <Button android:id="@+id/sliding_menu" android:layout_width="@dimen/header_height" android:layout_height="match_parent" android:layout_alignParentStart="true" /> <TextView android:layout_centerInParent="true" android:id="@+id/activity_title" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/filter_menu" android:layout_width="@dimen/header_height" android:layout_height="match_parent" android:layout_alignParentEnd="true" /> </RelativeLayout>
Let's explain the most important parts of it. First of all, we have defined RelativeLayout as our main container. Since all elements are positioned relatively to the parent and to each other, we will use some special attributes to express these relationships.
For every view, we must have width and height attributes. Values for it can be as follows:
- Dimension defined in the dimension resource file, for example:
android:layout_height="@dimen/header_height"
- Directly defined dimension value, for example:
android:layout_height="50dp"
- Match the size of the parent (match_parent)
- Or wrap the content of the view (wrap_content)
Then, we will populate the layout with children views. We have three children views. We will define two buttons and one text view. Text view is aligned to the center of the layout. Buttons are aligned with edges of the layout--one to the left and the other to the right. To achieve central alignment of the text view, we used the layout_centerInParent attribute. The value passed to it is the Boolean true. To align a button at the layout's left edge, we used the layout_alignParentStart attribute. For the right edge, we used the layout_alignParentEnd attribute. Each child has a proper ID assigned. We will include this in MainActivity:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/activity_header" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/items" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@android:color/darker_gray" /> <android.support.design.widget.FloatingActionButton android:id="@+id/new_item" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" android:layout_margin="@dimen/button_margin" /> </RelativeLayout> </LinearLayout>
The main container for Main activity is LinearLayout. An orientation attribute for LinearLayout is mandatory:
android:orientation="vertical"
Values that can be assigned to it are vertical and horizontal. As the first child of the Main activity, we included the activity_header layout. Then we defined RelativeLayout, which fills the rest of screen.
RelativeLayout has two members, ListView that will present all our items. We assigned a background to it. We did not define our own color in the colors resource file, but the one predefined in Android. Last view we have here is FloatingActionButton, the same one you can see in the Gmail Android application. The button will be positioned over the list with items at the bottom of the screen aligned to the right. We also set a margin that will surround the button from all sides. Take a look at the attributes we used.
Before we run our application again, we will make a few more changes. Open BaseActivity and update its code as follows:
... protected abstract fun getActivityTitle(): Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(getLayout()) activity_title.setText(getActivityTitle()) Log.v(tag, "[ ON CREATE ]") } ...
We introduced the abstract method that will provide a proper title for each activity. We will access the activity_title view defined in activity_header.xml, which is included in our activity, and assign the value we get by executing the method.
Open MainActivity and override the following method:
override fun getActivityTitle() = R.string.app_name
Add the same line to ItemActivity. Finally, run the application. Your main screen should look like this:

Let's define layouts for the rest of the screens. For the Notes, Add/Edit note screen, we will define the following layout:
<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android=
"http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <include layout="@layout/activity_header" /> <EditText android:id="@+id/note_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/title" android:padding="@dimen/form_padding" /> <EditText android:id="@+id/note_content" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="top" android:hint="@string/your_note_content_goes_here" android:padding="@dimen/form_padding" /> </LinearLayout> </ScrollView>
There are a few important things that we must highlight. We will explain them one by one. We introduced ScrollView as our top container for the layout. Since we will populate multiline notes, it will happen that its content goes below the physical limit of the screen. If that happens, we will be able to scroll the content. We used one very important attribute--fillViewport. This attribute tells the container to stretch to the whole screen. All children use that space.
- 小程序?qū)崙?zhàn)視頻課:微信小程序開發(fā)全案精講
- 數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)明教程(第2版)微課版
- Hands-On GPU:Accelerated Computer Vision with OpenCV and CUDA
- Microsoft System Center Orchestrator 2012 R2 Essentials
- C++ 從入門到項(xiàng)目實(shí)踐(超值版)
- VMware虛擬化技術(shù)
- 高級(jí)語言程序設(shè)計(jì)(C語言版):基于計(jì)算思維能力培養(yǎng)
- Getting Started with Gulp
- Learning JavaScript Data Structures and Algorithms
- 劍指大數(shù)據(jù):企業(yè)級(jí)數(shù)據(jù)倉庫項(xiàng)目實(shí)戰(zhàn)(在線教育版)
- 微服務(wù)從小白到專家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- Scala for Machine Learning(Second Edition)
- OpenCV 3 Blueprints
- Developer,Advocate!
- MySQL核心技術(shù)與最佳實(shí)踐