Welcome back to my ongoing blog series on the Basics of Android development. Today we will be discussing the buttons widget.
Task 1: Create and explore a new project
Open the Android Studio and, on the splash screen, click on Start a new Android Studio project. After clicking on it, the IDE will ask you to choose your project. Make sure you are on the Phone and Tablet tab, click on the Empty Activity option, then click on Next.
After clicking on this button, the IDE will show you a form that you can fill in as follows:
- Name: “Button Demo”
- Package name: com.nerdytech.buttondemo
- Save location: Use the default value or adjust to your needs.
- Language: “Java”
- Minimum API level: “API 21: Android 5.1 (Lollipop)”
From the properties above, there are two items that you can change: name and save location. Apart from that, you can also change the package name, but be aware that this tutorial uses this value multiple times (so, you will have to replace them a lot too). The other two properties, language, and minimum API level, must remain untouched. So, leave them like that and click on the Finish button.
Explore the layout editor
Android Studio provides the layout editor for quickly building an app’s layout of user interface (UI) elements. It lets you drag elements to a visual design and blueprint view, position them in the layout, add constraints, and set attributes. Constraints determine the position of a UI element within the layout. A constraint represents a connection or alignment to another view, the parent layout, or an invisible guideline.
Explore the layout editor, and refer to the figure below as you follow the numbered steps:
- In the app > res > layout folder in the Project > Android pane, double-click the activity_main.xml file to open it, if it is not already open.
- Click the Design tab if it is not already selected. You use the Design tab to manipulate elements and the layout, and the Text tab to edit the XML code for the layout.
- The Palettes pane shows UI elements that you can use in your app’s layout.
- The Component tree pane shows the view hierarchy of UI elements.
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, theTextView
is a child of theConstraintLayout
. You will learn about these elements later in this lesson. - The design and blueprint panes of the layout editor showing the UI elements in the layout. In the figure above, the layout shows only one element: a TextView that displays “Hello World”.
- The Attributes tab displays the Attributes pane for setting properties for a UI element.
Task 2: Add View elements in the layout editor by using Widgets Pallete.
In this task, you create the UI layout for the Button Demo app in the layout editor using the ConstraintLayout
features. You can create the constraints manually, as shown later, or automatically using the Autoconnect tool.
2.1 Examine the element constraints
Follow these steps:
- Open
activity_main.xml
from the Project > Android pane if it is not already open. If the Design tab is not already selected, click it.
- If there is no blueprint, click the Select Design Surface button in the toolbar and choose Design + Blueprint.
- The Autoconnect tool is also located in the toolbar. It is enabled by default. For this step, ensure that the tool is not disabled.
- Click the zoom in button to zoom into the design and blueprint panes for a close-up look.
2. Select TextView in the Component Tree pane. The “Hello World” TextView
is highlighted in the design and blueprint panes and the constraints for the element are visible.
3. Refer to the animated figure below for this step. Click the circular handle on the right side of the TextView
to delete the horizontal constraint that binds the view to the right side of the layout. The TextView
jumps to the left side because it is no longer constrained to the right side. To add back the horizontal constraint, click the same handle and drag a line to the right side of the layout.
In the blueprint or design panes, the following handles appear on the TextView
element:
- Constraint handle: To create a constraint as shown in the animated figure above, click a constraint handle, shown as a circle on the side of an element. Then drag the handle to another constraint handle, or to a parent boundary. A zigzag line represents the constraint.
- Resizing handle: To resize the element, drag the square resizing handles. The handle changes to an angled corner while you are dragging it.
2.2 Add a Button to the layout
When enabled, the Autoconnect tool automatically creates two or more constraints for a UI element to the parent layout. After you drag the element to the layout, it creates constraints based on the element’s position.
Follow these steps to add a Button
:
- Start with a clean slate. The
TextView
element is not needed, so while it is still selected, press the Delete key or choose Edit > Delete. You now have a completely blank layout. - Drag a Button from the Palette pane to any position in the layout. If you drop the
Button
in the top middle area of the layout, constraints may automatically appear. If not, you can drag constraints to the top, left side, and right side of the layout as shown in the video below.
Task 2.3 change attributes of the button
- Change button Id attribute to LogBtn
- Change Button text to attribute to “Log Button”
- Change button to size to match the parent.
- Add a margin of 8px to top, left and right of the button.
- Change the color of the button background by editing the background attribute.
- Change the color of the text in button by editing the textColor attribute.
Given Below is a video for guiding you to perform the above steps if you get stuck.
Task 3 Add another Button via XML code.
Switch to the text tab to code the XML of the new button. Add this code below the existing button code and it will create a new button.
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/LogBtn2"/>
<Button/> is an XML tag for the button widget. The attributes android:layout_width=“match_parent”, android:layout_height=“wrap_content” are defining the buttons basic width and height. The value match_parent will define the width of the button to be the same as that of the constraint_layout and the value wrap_content will define that the height of the button will be the enclosing text inside the button. The attribute android:id=“@+id/LogBtn2" will give a unique identity for that button which will be used to reference it in the future for various operations.
Now add attributes of position and size just below the id attribute.
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toEndOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/LogBtn"
The layout_marginTop, layout_marginStart, and layout_marginEnd are the attributes that will leave a margin of 8dp from the top, start and bottom s that the button doesn't touch the edge of the screen and there is some space left.
The app:layout_constraintStart_toEndOf=“parent”, app:layout_constraintEnd_toEndOf=“parent” are the attributes that tell that constraint of Start and end are of those of the parent, i.e, they should not exceed the constraints of its parent.
The app:layout_constraintTop_toBottomOf=“@id/LogBtn” attribute is telling that the top constraint of LogBtn2 should start from the end of LogBtn.
Now let's add the text, text color, and button background color properties.
android:text="Log Button2"
android:textColor="@android:color/white"
android:background="@color/colorPrimary"
After you have added all the attributes in your button the code should look like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<Button
android:id="@+id/LogBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="@color/colorPrimaryDark"
android:text="Log Button"
android:textColor="@android:color/background_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/LogBtn2"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
app:layout_constraintStart_toEndOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/LogBtn"
android:text="Log Button2"
android:textColor="@android:color/white"
android:background="@color/colorPrimary"/>
</androidx.constraintlayout.widget.ConstraintLayout>
And your design should look something like this:
If you have faced any issue you can follow along with this video below:
Task 4: Add on click handlers on the buttons
Navigate to MainActivity.java file app>java>com.nerdytech.buttondemo or in your case app>java>com.example.buttondemo
Now add the button widgets as global variables in the MainActivity class.
//widgets
Button LogBtn,LogBtn2;
Press Alt+Enter if there is an error highlighting the Button.
Now in the onCreate method link the global variable to the resource files that we had created in activity_main.xml. We can do that by calling an inbuilt function View.findViewById(). This function takes in parameters as R.id.id_ofElement. R here refers to the resource-“res” directory. the id contains all the id values that have been created in the project. You need to replace the id_ofElement with a proper id that you have provided while designing the widget element in your XML file.
Add these lines below setContentView(R.layout.activity_main); line in onCreate method.
LogBtn=findViewById(R.id.LogBtn);
LogBtn2=findViewById(R.id.LogBtn2);
Now all the Widgets are linked properly with their proper widget elements in the XML file.
Let’s Add OnClickHandlers to buttons
We can do this in two ways. By creating our own method which will be called when the button is pressed or by overriding the setOnClickListner method.
Method 1:Create a new method called LogBtnOnPressed.
public void LogBtnOnPressed(View view){
Log.i("LogBtn","Pressed!");
}
This method takes a View as a parameter. Now navigate back to activity_xml and add an attribute to the LogBtn button.
android:onClick="LogBtnOnPressed"
The button tag will look like this:
<Button
android:id="@+id/LogBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:background="@color/colorPrimaryDark"
android:onClick="LogBtnOnPressed"
android:text="Log Button"
android:textColor="@android:color/background_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Method 2: Override the setOnClickListner method in the onCreate method. after the line `LogBtn2=findViewById(R.id.LogBtn2);` add this.
LogBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("LogBtn2","Pressed!");
}
});
This will work the same as method 1. the only difference is the method of implementation.
Lastly, Check the app output in logcat by running the app in an emulator or your real device. When you press Log Button in logcat a line will be added similar to this-
2020–04–11 15:40:33.265 7696–7696/com.nerdytech.buttondemo I/LogBtn: Pressed!
When you press Log Button2 in logcat a line will be added similar to this-
2020-04-11 15:40:42.482 7696-7696/com.nerdytech.buttondemo I/LogBtn2: Pressed!
If you have faced any error, please follow along with this video:
What's next- Android Tutorials- Part 2.3.0-Edit Text.