An Android Java ConstraintSet Example

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 put these concepts into practice by creating an example layout created entirely in Java code and without using the Android Studio Layout Editor tool.

Creating the Example Project in Android Studio

Launch Android Studio and select the New Project option from the welcome screen and, within the resulting new project dialog, choose the Empty Views 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.

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:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Iguana – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 840 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

@Override
protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
    // setContentView(R.layout.activity_main);
}Code language: JavaScript (javascript)

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;
import android.widget.Button;
import android.widget.EditText;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);     
        configureLayout();
    }
 
    private void configureLayout() {
        Button myButton = new Button(this);
        ConstraintLayout myLayout = new ConstraintLayout(this);
        myLayout.addView(myButton);
        setContentView(myLayout);
    }
}Code language: Java (java)

When new instances of user interface objects are created in this way, the constructor methods must be passed the context within which the object is being created, which, in this case, is the current activity. Since the above code resides within the activity class, the context is referenced by the standard this keyword:

Button myButton = new Button(<strong>this</strong>);Code language: Java (java)

Once the above additions have been made, compile and run the application (either on a physical device or an emulator). Once launched, the visible result will be a button containing no text appearing in the top left-hand corner of the ConstraintLayout view, as shown in Figure 31-1:

Figure 24-1

Setting View Attributes

For 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. These tasks can be achieved by setting attributes on the views in the Java code as outlined in the following code fragment. 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>Code language: HTML, XML (xml)

Although this is the recommended way to handle strings directly referenced in code, many subsequent code samples will directly enter strings into the code to avoid repetition of this step throughout the remainder of the book.

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Iguana – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 840 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Once the string is stored as a resource, it can be accessed from within the code as follows:

getString(R.string.press_me);Code language: Java (java)

With the string resource created, add code to the configureLayout() method to set the button text and color attributes:

.
.
import android.graphics.Color;
 
public class MainActivity extends AppCompatActivity {
 
    private void configureLayout() {
        Button myButton = new Button(this);
        myButton.setText(getString(R.string.press_me));
        myButton.setBackgroundColor(Color.YELLOW);
 
        ConstraintLayout myLayout = new ConstraintLayout(this);
        myLayout.setBackgroundColor(Color.BLUE);
 
        myLayout.addView(myButton);
        setContentView(myLayout);
}Code language: Java (java)

When the application is compiled and run, the layout will reflect the property settings such that the layout will appear with a blue background, and the button will display the assigned text on a yellow background.

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:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Iguana – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 840 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="myButton" type="id" />
    <item name="myEditText" type="id" />
</resources>Code language: HTML, XML (xml)

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() {
    Button myButton = new Button(this);
    myButton.setText(getString(R.string.press_me));
    myButton.setBackgroundColor(Color.YELLOW);
    myButton.setId(R.id.myButton);
.
.Code language: Java (java)

Configuring the Constraint Set

Without constraints, the ConstraintLayout view has placed the Button view in the display’s top left corner. 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 displays 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(Color.YELLOW);
    myButton.setId(R.id.myButton);
 
    ConstraintLayout myLayout = new ConstraintLayout(this);
    myLayout.setBackgroundColor(Color.BLUE);
 
    myLayout.addView(myButton);
    setContentView(myLayout);
 
    ConstraintSet set = new ConstraintSet();
    
    set.constrainHeight(myButton.getId(),
            ConstraintSet.WRAP_CONTENT);
    set.constrainWidth(myButton.getId(),
            ConstraintSet.WRAP_CONTENT);
    
    set.connect(myButton.getId(), ConstraintSet.START,
            ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
    set.connect(myButton.getId(), ConstraintSet.END,
            ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
    set.connect(myButton.getId(), ConstraintSet.TOP,
            ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
    set.connect(myButton.getId(), ConstraintSet.BOTTOM,
            ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
    
    set.applyTo(myLayout);
}Code language: Java (java)

With the initial constraints configured, compile and run the application and verify that the Button view now appears in the center of the layout:

Figure 24-2

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 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:

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Iguana – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 840 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

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);
    myLayout.addView(myEditText);
 
    setContentView(myLayout);
.
.
}Code language: Java (java)

The EditText widget is intended to be sized subject to the content it displays, centered horizontally within the layout, and positioned 70dp above the existing Button view. Add code to the configureLayout() method so that it reads as follows:

.
.
set.connect(myButton.getId(), ConstraintSet.START, 
              ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
set.connect(myButton.getId(), ConstraintSet.END, 
              ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
set.connect(myButton.getId(), ConstraintSet.TOP, 
              ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
set.connect(myButton.getId(), ConstraintSet.BOTTOM, 
              ConstraintSet.PARENT_ID, ConstraintSet.BOTTOM, 0);
 
set.constrainHeight(myEditText.getId(), 
                         ConstraintSet.WRAP_CONTENT);
set.constrainWidth(myEditText.getId(), 
                         ConstraintSet.WRAP_CONTENT);
 
set.connect(myEditText.getId(), ConstraintSet.START, 
              ConstraintSet.PARENT_ID, ConstraintSet.START, 0);
set.connect(myEditText.getId(), ConstraintSet.END, 
              ConstraintSet.PARENT_ID, ConstraintSet.END, 0);
set.connect(myEditText.getId(), ConstraintSet.BOTTOM, 
              myButton.getId(), ConstraintSet.TOP, 70);
 
set.applyTo(myLayout);Code language: Java (java)

A test run of the application should show the EditText field centered above the button with a margin of 70dp.

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). To set a position using dp, it is necessary to convert a dp value to a px value at runtime, considering 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 r = getResources();
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, value,
                r.getDisplayMetrics());
    }
 
    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);
    
        int px = convertToPx(200);
        myEditText.setWidth(px);
.
.
}Code language: Java (java)

Compile and run the application one more time and note that the width of the EditText view has changed, as illustrated in Figure 31-3:

Figure 24-3

Summary

The example activity created in this chapter has 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.

 

 

Get the Updated Book

You are reading a sample chapter from an old edition of the Android Studio Essentials – Java Edition book.

Purchase the fully updated Android Studio Iguana – Java Edition of this book in eBook or Print format.

The full book contains 92 chapters and over 840 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

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


Categories ,