Professional Documents
Culture Documents
Lab 4b - Simple Calculator App
Lab 4b - Simple Calculator App
Sem. II 2019/2020
Lab Exercise 4b: Android Simple Programming – Calculator app
1. TextView
2. Buttons
TextView
We use the textView to show users the numbers they have written and also to display
the result of the calculations we are going to do.
Buttons
Each of the numbers will have a different button, from 0-9 and we will have four
additional buttons for addition, subtraction, multiplication and division.
Other than this, we require a button to calculate the operation, a button for decimals,
and a button to clear the display.
Requirements
EditText To display numbers and the result.
Button Digits 0-9
Button Operational buttons (+, -, *, /, =)
Button Decimal button
Button Clear display button
Layout – RelativeLayout
Step 2: Coding the Functionality – MainActivity.java
i. Creating objects for the UI elements in activity_main.xml file.
Create objects for all 15+ buttons and an object for the EditText.
EditText ed1;
Inside the onCreate function, fetch all values and assign it to the created object
in (i) using the findViewById() method.
btn_0 = (Button)findViewById(R.id.btn_0);
:
.
ed1 = (EditText)findViewById(R.id.edText1);
Fetching the value of ‘btn_0’, which is the ID of the button zero, and storing it
in the object ‘btn_0’ that created earlier in the main activity file.
btn_0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ed1.setText(ed1.getText()+”0”);
}
});
:
.
The editText already fetches the value that it is already displaying, null in this
case, and then adds 0 to it.
If don’t fetch the existing value then it becomes impossible to enter multiple digit
numbers.
Do this on repeat mode for each of the numbers as well as the decimal.
btn_Add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(ed1 == null){
ed1.setText(“”);
}else
Value1 = Float.parseFloat(ed1.getText()
+ “”);
isAdd = true;
ed1.setText(null);
}
}
});
:
.
Use the simple function getText() to handle the operation. Since the addition
button is pressed, set it’s boolean equivalent variable to true. After press the add
button we have to input another number set EditText to display null value.
btn_calc.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
Value2 = Float.parseFloat(ed1.getText() +
“”);
if(isAdd == true) {
ed1.setText(Value1 + Value2 +””);
isAdd = false;
}
if(isSub == true) {
ed1.setText(Value1 – Value2 +””);
isSub = false;
}
:
.
});
btn_clear.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
ed1.setText(“”);
});