Defining dimension resources

Typically in a layout file, we can have numerous elements that specify the same constraint values to attributes. Such values should be added to a dimensions resource file. Let's go ahead and create a dimensions resource file now. In your application project view, navigate to res | values and create a new value resource file in the directory with the name dimens:

Leave all other file attributes at their default values:

Open the file upon its creation. Its content should be similar to the following code:

<?xml version="1.0" encoding="utf-8"?>
<resources></resources>

The first line of dimens.xml declares the XML version and character encoding used within the file. The second line contains a <resources> resources tag. Our dimensions will be declared within this tag. Add a few dimension values, as demonstrated in the following code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="layout_margin_top">16dp</dimen>
<dimen name="layout_margin_bottom">16dp</dimen>
<dimen name="layout_margin_start">16dp</dimen>
<dimen name="layout_margin_end">16dp</dimen>
<dimen name="layout_margin_vertical">16dp</dimen>
</resources>

New dimensions are declared using the <dimen> tag. Dimension names should typically be written in snake case. The value for a dimension is added within the opening <dimen> and closing </dimens> tags.

Now that we have added a few dimensions, we can use them in our linear layout:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.mydomain.tetris.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="@dimen/layout_margin_top"
<!— layout_margin_top dimension reference —>
android:layout_marginBottom="@dimen/layout_margin_bottom"
<!— layout_margin_top dimension reference —>
android:orientation="vertical"
android:gravity="center_horizontal">
</LinearLayout>
</android.support.constraint.ConstraintLayout>

We've gotten our LinearLayout view group set up and now we need to add the required layout views to it. Before we do that, we need to understand the concepts of views and view groups.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.66