Learn Android — Adding Interaction
The world’s most popular mobile OS — from phones and watches to cars and TVs.
Welcome to the Learn Android series. I’m going to share with you, weekly, why and how to start with Android and build your portfolio. I’ll share with you explanations and code snippets on how to implement the most important and basic things in Android.
In the previous article, we learned how to create beautiful and responsive User Interface layouts using the Android’s latest official library, the Constraint Layout. After completing the UI, we need to make it work and respond to actions / events like text input, button click and more. We will learn all of these in this article.
Once we have created the layouts using XML, we need to move on to the logic part to make our application interactive in terms of responding back to the user.
So to make a view or component interactive, we first need to reference them into the Java file from the XML. This is where the android:id attribute comes into use. We first create an object instance of the view we want to initialize, and then reference the view to the XML element using the id. To reference, we use the inbuilt function findViewById() and pass in the id as a parameter. Let’s create an Compose Email layout to understand how to implement this —
First we’ll create the XML layout. Check out the different attributes that have been used to get best results. Here is the layout code —
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Enter first number: "
android:textColor="@android:color/black"
android:textSize="16sp" />
<EditText
android:id="@+id/first_num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:hint="Enter number here"
android:inputType="numberDecimal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:text="Enter second number: "
android:textColor="@android:color/black"
android:textSize="16sp" />
<EditText
android:id="@+id/second_num"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginEnd="16dp"
android:layout_marginStart="16dp"
android:hint="Enter number here"
android:inputType="numberDecimal" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="horizontal"
android:padding="16dp">
<Button
android:id="@+id/add_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:text="Add"
android:textColor="@android:color/black"
android:textSize="16sp" />
<Button
android:id="@+id/sub_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:text="Subtract"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:orientation="horizontal"
android:padding="16dp">
<Button
android:id="@+id/mult_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:text="Multiply"
android:textColor="@android:color/black"
android:textSize="16sp" />
<Button
android:id="@+id/div_btn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@android:color/transparent"
android:text="Divide"
android:textColor="@android:color/black"
android:textSize="16sp" />
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:gravity="center"
android:hint="Result here"
android:textColor="@color/colorPrimary"
android:textSize="20sp" />
</LinearLayout>
We’ve understood how to create layouts in one of the previous articles, so we won’t discuss that here. But this is how the layout will look like —
Let’s move on to the logic part. We will first create instance of the view components and reference those from the XML using ID’s.
public class MainActivity extends AppCompatActivity {
//Creating object instances of the views that we've defined in the XML.
private EditText number1, number2;
private Button addButton, subButton, multButton, divButton;
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Referencing the view components from the XML using their respective ID's.
number1 = findViewById(R.id.first_num);
number2 = findViewById(R.id.second_num);
addButton = findViewById(R.id.add_btn);
subButton = findViewById(R.id.sub_btn);
multButton = findViewById(R.id.mult_btn);
divButton = findViewById(R.id.div_btn);
result = findViewById(R.id.result_tv);
}
}
Since we have 3 EditText’s in XML we create 3 EditText objects with relatable names. We also create a Button object (the send button). Now to reference to the XML, we use the inbuilt function findViewById() and pass in the integer parameter — the resource id. If Android Studio displays an error or you are unable to reference to the id, “Clean Project” by going to Build → Clean Project.
Now, you must be wondering what is the R.id logic! Well, every time we initialize a view with an ID, the Android Studio generates an integer value to encode the ID and this is stored in the resource file. Let’s have a look at how the resource file is —
You should not directly alter the contents of this file, unless you are very much confident of what you intend to do. This R.java file stores all the integer values for all different resource types including layouts, strings, styles, colors, and more.
Now, let’s see how we can make these interactive. There are two ways to make a button interactive.
- Define a function in the Java file and call them in the XML. But this isn’t the best way to do it, so let’s look at the second one. To learn more about the onClick attribute in XML, please have a look at the documentation!
- Defining all the logic and calling in the same Java file! This is the most common implementation and we’ll have a look at this.
Initially, we will let the user enter the numbers and those will perform respective operations as we click on the buttons, which will display the result in the Result TextView that we created. Let’s code for the buttons.
Now as soon as the user clicks on the button, we’ll have to update the TextView. But first we’ll have to retrieve the number from the input field. Note that in the XML, we have limited the input to only NumberDecimal format so there is no text entry which can cause errors. To set up a click event for a button in Android, we need to let Android listen for “click events”. This is done using the onClickListener() method.
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(number1.getText().toString());
int num2 = Integer.parseInt(number2.getText().toString());
int answer = num1 + num2;
result.setText(String.valueOf(answer));
}
});
This might look overwhelming at first, but you just need to enter the name of object (addButton in this case) and start typing for onClickListener() and the Android Studio IDE will automatically complete all the extra implementation. Then we write the logic for retrieving of numbers. We use both the Edit Text objects and call the getText().toString() function on it, to get the string value entered by the user. Next we convert them to integers and add both of them, since this is to be implemented when clicking on the addButton object.
Then finally, we set the string value back again to the Text View object for the Result, which displays our answer for the calculation we just performed, using the setText() method.
If you want to know about the different methods, or how to implement something, please do have a look at the widget section of the Android Documentation! There are thousands of components and you don’t have to remember all the methods. Just Google them whenever you need to know how to implement something. With time, you’ll even start remembering the most common and most important ones.
We carry out similar process for other buttons. Try them on your own and if you are stuck, here is the code you can refer to —
subButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(number1.getText().toString());
int num2 = Integer.parseInt(number2.getText().toString());
int answer = num1 - num2;
result.setText(String.valueOf(answer));
}
});
multButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(number1.getText().toString());
int num2 = Integer.parseInt(number2.getText().toString());
int answer = num1 * num2;
result.setText(String.valueOf(answer));
}
});
divButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int num1 = Integer.parseInt(number1.getText().toString());
int num2 = Integer.parseInt(number2.getText().toString());
int answer = 0;
if (num2 != 0) {
answer = num1 / num2;
result.setText(String.valueOf(answer));
}
result.setText(String.valueOf(answer));
}
});
All the code logic is similar except for the division, because we will have to check for 0 in the denominator. If you run this code, you can see that the results will be displayed in the Result TextView that we have created and initialized.
You have made the application respond to user clicks! Go on! Show off to your friends and family and tell them about the amazing journey you’ve started being a part of!