Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Java Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815161
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

24. An Android ConstraintSet Tutorial

The previous chapter introduced the basic concepts of creating and modifying user interface layouts in Java code using the ConstraintLayout and ConstraintSet classes. This chapter will take these concepts and put them into practice through the creation of an example layout created entirely in Java code and without using the Android Studio Layout Editor tool.

24.1 Creating the Example Project in Android Studio

Launch Android Studio and select the Create New Project option from the quick start menu in the welcome screen and, within the resulting new project dialog, choose the Empty Activity template before clicking on the Next button.

Enter JavaLayout into the Name field and specify com.ebookfrenzy.javalayout as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Java.

Once the project has been created, the MainActivity.java file should automatically load into the editing panel. As we have come to expect, Android Studio has created a template activity and overridden the onCreate() method, providing an ideal location for Java code to be added to create a user interface.

24.2 Adding Views to an Activity

The onCreate() method is currently designed to use a resource layout file for the user interface. Begin, therefore, by deleting this line from the method:

@Override

protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       setContentView(R.layout.activity_main);

}

The next modification is to add a ConstraintLayout object with a single Button view child to the activity. This involves the creation of new instances of the ConstraintLayout and Button classes. The Button view then needs to be added as a child to the ConstraintLayout view which, in turn, is displayed via a call to the setContentView() method of the activity instance:

package com.ebookfrenzy.javalayout;

 

import androidx.appcompat.app.AppCompatActivity;

 

import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout...

24.3 Setting View Attributes

For the purposes of this exercise, we need the background of the ConstraintLayout view to be blue and the Button view to display text that reads “Press Me” on a yellow background. Both of these tasks can be achieved by setting attributes on the views in the Java code as outlined in the following code fragment. In order to allow the text on the button to be easily translated to other languages it will be added as a String resource. Within the Project tool window, locate the app -> res -> values -> strings.xml file and modify it to add a resource value for the “Press Me” string:

<resources>

    <string name="app_name">JavaLayout</string>

    <string name="press_me">Press Me</string>

</resources>

Although this is the recommended way to handle strings that are directly referenced in code, to avoid repetition of...

24.4 Creating View IDs

When the layout is complete it will consist of a Button and an EditText view. Before these views can be referenced within the methods of the ConstraintSet class, they must be assigned unique view IDs. The first step in this process is to create a new resource file containing these ID values.

Right click on the app -> res -> values folder, select the New -> Values resource file menu option and name the new resource file id.xml. With the resource file created, edit it so that it reads as follows:

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

<resources>

    <item name="myButton" type="id" />

    <item name="myEditText" type="id" />

</resources>

At this point in the tutorial, only the Button has been created, so edit the configureLayout() method to assign the corresponding ID to the object:

private void configureLayout...

24.5 Configuring the Constraint Set

In the absence of any constraints, the ConstraintLayout view has placed the Button view in the top left corner of the display. In order to instruct the layout view to place the button in a different location, in this case centered both horizontally and vertically, it will be necessary to create a ConstraintSet instance, initialize it with the appropriate settings and apply it to the parent layout.

For this example, the button needs to be configured so that the width and height are constrained to the size of the text it is displaying and the view centered within the parent layout. Edit the configureLayout() method once more to make these changes:

.

.

import androidx.constraintlayout.widget.ConstraintSet;

.

.

private void configureLayout() {

    Button myButton = new Button(this);

    myButton.setText(getString(R.string.press_me));

    myButton.setBackgroundColor...

24.6 Adding the EditText View

The next item to be added to the layout is the EditText view. The first step is to create the EditText object, assign it the ID as declared in the id.xml resource file and add it to the layout. The code changes to achieve these steps now need to be made to the configureLayout() method as follows:

private void configureLayout() {

    Button myButton = new Button(this);

    myButton.setText(getString(R.string.press_me));

    myButton.setBackgroundColor(Color.YELLOW);

    myButton.setId(R.id.myButton);

 

    EditText myEditText = new EditText(this);

    myEditText.setId(R.id.myEditText);

 

    ConstraintLayout myLayout = new ConstraintLayout(this);

    myLayout.setBackgroundColor(Color.BLUE);

 

    myLayout.addView(myButton)...

24.7 Converting Density Independent Pixels (dp) to Pixels (px)

The next task in this exercise is to set the width of the EditText view to 200dp. As outlined in the chapter entitled “An Android Studio Layout Editor ConstraintLayout Tutorial” when setting sizes and positions in user interface layouts it is better to use density independent pixels (dp) rather than pixels (px). In order to set a position using dp it is necessary to convert a dp value to a px value at runtime, taking into consideration the density of the device display. In order, therefore, to set the width of the EditText view to 200dp, the following code needs to be added to the class:

package com.ebookfrenzy.javalayout;

.

.

import android.content.res.Resources;

import android.util.TypedValue;

 

public class MainActivity extends AppCompatActivity {

 

    private int convertToPx(int value) {

        Resources...

24.8 Summary

The example activity created in this chapter has, of course, created a similar user interface (the change in background color and view type notwithstanding) as that created in the earlier “Manual XML Layout Design in Android Studio” chapter. If nothing else, this chapter should have provided an appreciation of the level to which the Android Studio Layout Editor tool and XML resources shield the developer from many of the complexities of creating Android user interface layouts.

There are, however, instances where it makes sense to create a user interface in Java. This approach is most useful, for example, when creating dynamic user interface layouts.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Java Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815161
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth