Cách dụng Calculator trên Android

Ứng dụng máy tính là một trong những ứng dụng phổ biến nhất, hầu như mọi điện thoại đều tích hợp sẵn. Bạn sẽ gặp rất nhiều ứng dụng calculator online ở rất nhiều nơi, từ mobile tới PC, kể cả web app. Bạn có muốn tự mình tạo một ứng dụng như vậy không?

Trong bài viết này, mình sẽ hướng dẫn rất chi tiết cách tạo ứng dụng Calculator Android đơn giản sử dụng Android Studio. Với những chức năng cơ bản như: cộng, trừ, nhân, chia, logarit, lập phương, căn bậc hai, căn bậc ba.

Trước khi bắt đầu, hãy xem qua giao diện ứng dụng sau khi bạn hoàn thành bài viết này.

Ứng dụng này có một nút Clear để xóa lịch sử tính toán trên màn hình. Người dùng nhấn phím Enter để hiển thị kết quả tính toán. Vùng giao diện đen phía trên cùng để hiển thị dữ liệu người nhập.

Cách dụng Calculator trên Android
Giao diện ứng dụng máy tính Android

Từng bước tạo ứng dụng Calculator

Để tạo 1 ứng dụng như trên, bạn làm theo các bước sau đây:

Bước 1. Mở Android Studio và tạo mới một New Project tên là My Calculator. Nếu chưa thạo cách sử dụng Android Studio thì xem hình dưới nhé.

Cách dụng Calculator trên Android
Tạo mới một project trong android

Bước 2. Chọn API 16 và sau đó tạo một Empy Activity.
Bước 3. Tiếp theo, hãy kéo thả 2 TextView vào giao diện Design của activity_main.xml và thực hiện như sau:

  • Thay đổi thuộc tính file, thiết lập lại màu sắc textview1 thành màu đen (#000000) và textview2 (nơi kết quả được hiển thị) thành màu xanh lá cây (#02b54b), loại bỏ phần lề.
  • Thiết lập phần lề dưới = 8sp và thiết lập chiều ngang = match_parent và chiều cao = wrap_content.
  • Tiếp đến, chúng ta thay đổi căn chỉnh văn bản của cả 2 TextViews.
  • Thiết lập ID là txt1 và txt2.
  • Giới hạn kích thước 4 phía của txt1và giới hạn txt2 dưới txt1. Để biết thêm thông tin hãy xem mã bên dưới.

Bước 4. Kéo Linear Layout ở phía dưới của textview và chèn 4 nút (button).

  • Thiết lập Linear layout với chiều rộng là match_parent và chiều cao là wrap_content.
  • Thiết lập định hướng trang là horizontal.
  • Giới hạn layout dưới txt2 như trong code phía dưới.
  • Thay đổi màu button và thiết lập chiều rộng và chiều cao là wrap_content.
  • Thêm ID và text tương ứng vào các nút.

Cách dụng Calculator trên Android

Bước 5. Chèn phía dưới Linear layout một layour khác và giới hạn layout này với Linear layout phía trên. Thiết lập ID giống như trên và thay đổi các text tương ứng.

Đừng bỏ lỡ: Lập trình ứng dụng cho di động Có nên chọn nghề này không?

Bước 6. Tương tự như vậy, chúng ta tạo 2 nút Enter và Clear bằng cách kéo 2 nút vào layout phía dưới.

Cách dụng Calculator trên Android

Nếu vẫn thấy khó hiểu thì các bạn hãy sử dụng Code dưới đây (activity_main.xml).

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.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" android:background="#606060" tools:context="com.faultinmycode.mycalculator.MainActivity"> <TextView android:id="@+id/txt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="8sp" android:background="#000000" android:textAlignment="textEnd" android:textColor="#ffffff" android:textSize="25sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.025" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.016" /> <TextView android:id="@+id/txt2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8sp" android:background="#02b54b" android:textAlignment="textEnd" android:textColor="#ffffff" android:textSize="50sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="@+id/txt1" app:layout_constraintTop_toBottomOf="@+id/txt1" /> <LinearLayout android:id="@+id/linearLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8sp" android:layout_marginTop="8sp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@id/txt2" app:layout_constraintTop_toBottomOf="@+id/txt2"> <Button android:id="@+id/add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="Add" /> <Button android:id="@+id/sub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="Subtract" /> <Button android:id="@+id/mul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="Multiply" /> <Button android:id="@+id/div" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="Division" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8sp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout" tools:layout_editor_absoluteY="212dp"> <Button android:id="@+id/nine" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="9" android:textSize="25sp" /> <Button android:id="@+id/eight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="8" android:textSize="25sp" /> <Button android:id="@+id/seven" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="7" android:textSize="25sp" /> <Button android:id="@+id/sq" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="x^2" android:textSize="25sp" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8sp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout2"> <Button android:id="@+id/six" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="6" android:textSize="25sp" /> <Button android:id="@+id/five" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="5" android:textSize="25sp" /> <Button android:id="@+id/four" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="4" android:textSize="25sp" /> <Button android:id="@+id/sqrt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="SQRT" android:textSize="25sp" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8sp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout3"> <Button android:id="@+id/three" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="3" android:textSize="25sp" /> <Button android:id="@+id/two" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="2" android:textSize="25sp" /> <Button android:id="@+id/one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="1" android:textSize="25sp" /> <Button android:id="@+id/zero" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="0" android:textSize="25sp" /> </LinearLayout> <LinearLayout android:id="@+id/linearLayout5" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="8sp" android:orientation="horizontal" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout4"> <Button android:id="@+id/log" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="Log10" android:textSize="25sp" /> <Button android:id="@+id/cub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="x^3" android:textSize="25sp" /> <Button android:id="@+id/cubroot" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="CubRT" android:textSize="25sp" /> <Button android:id="@+id/dec" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#e55c00" android:text="." android:textSize="25sp" /> </LinearLayout> <Button android:id="@+id/enter" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8sp" android:background="#77db35" android:text="Enter" android:textSize="25sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout5" app:layout_constraintVertical_bias="0.032" /> <Button android:id="@+id/clear" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="#007aff" android:text="Clear" android:textColor="#ffffff" android:textSize="25sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/enter" app:layout_constraintVertical_bias="0.074" /> </android.support.constraint.ConstraintLayout>

Bước 7. Bây giờ hãy vào MainActivity.java để viết code reference vào View và xử lý logic.

Reference các button và TextView với layout.

button = findViewById (R.id. [ Respective_ID);

Các nút từ 0-9 và số thập phân, chúng ta sử dụng setOnClickListener tạo ra tính năng onClick như trong code dưới đây.

TextView: txt1.setText(txt1.getText()+"1");

Sau đó chúng ta tạo một phương thức colorChange() để thay đổi màu sắc của toán tử:

public void colorChange(Button b){ b.setBackgroundColor(getResources().getColor(R.color.colorAccent)); }

Để reset màu sắc các nút về trạng thái ban đầu, chúng ta cần allReset()

public void allReset(){ [Button].setBackgroundColor(getResources().getColor(R.color.[Button_Color])); }

Bây giờ, để chạy phép toán chúng ta cần thiết lập những giá trị trong khoảng kết quả các phép toán. Tiếp đến, tạo hai cặp biến var1 và var2. Giá trị của chúng sẽ được lấy từ TextView (txt1)

Để thực hiện phép tính cộng trừ nhân chia, chúng phải là các con số. Do vậy, chúng ta sẽ ép kiểu từ String sang kiểu Double như sau:

public void setVar1(){ var1 = Double.parseDouble(txt1.getText().toString()); }
  • Sau đó, chúng ta gọi xử lý sự kiện click cho nút tính cộng bằng onClickListener
add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(add); buttonFalse(); addition = true; } });

Các phép toán trừ, chia và nhân trong tạo ứng dụng Calculator cũng thực hiện tương tự như trên.

Với các phép Logarit, căn bậc hai, bình phương và lập phương, chúng ta đã tạo các kết quả có sẵn mà không cần người dùng phải ấn Enter bởi vì mỗi phép toán chỉ có 1 kết quả duy nhất.

Enter là nút tính toán chính, nhưng trước đó chúng ta phải khai báo biến var2 và thêm xử lý sự kiện setOnClickListener() như đoạn code dưới:

var2 = Double.parseDouble(txt1.getText().toString());

Sử dụng hàm If-else để kiểm tra loại phép tính:

if(addition){ ans = var1 + var2; } else if (subtract){ ans = var1  var2; } else if (multiply){ ans = var1 * var2; } else if (divide){ ans = var1 / var2; } else { ans = ans + 0; }

Bây giờ hãy thiết lập ans cho txt2 và để vô hiệu hóa nút enter bằng cách sử dụng code sau:

txt2.setText(ans.toString()); enter.setEnabled(false);

Mã nguồn hoàn chỉnh của MainActivity.java

package com.faultinmycode.mycalculator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { Button b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, enter, add, sub, mul, div, clear, sq, sqrt; Button cb, cbrt, dec, log10; TextView txt1, txt2; Double var1; Double var2; Double ans; Boolean addition = false, subtract = false, multiply = false, divide = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = findViewById(R.id.one); b2 = findViewById(R.id.two); b3 = findViewById(R.id.three); b4 = findViewById(R.id.four); b5 = findViewById(R.id.five); b6 = findViewById(R.id.six); b7 = findViewById(R.id.seven); b8 = findViewById(R.id.eight); b9 = findViewById(R.id.nine); b0 = findViewById(R.id.zero); add = findViewById(R.id.add); sub = findViewById(R.id.sub); mul = findViewById(R.id.mul); div = findViewById(R.id.div); sq = findViewById(R.id.sq); sqrt = findViewById(R.id.sqrt); cb = findViewById(R.id.cub); cbrt= findViewById(R.id.cubroot); dec = findViewById(R.id.dec); log10 = findViewById(R.id.log); enter = findViewById(R.id.enter); clear = findViewById(R.id.clear); txt1 = findViewById(R.id.txt1); txt2 = findViewById(R.id.txt2); //to show value of this button in textView1 b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"1"); } }); //to show value of this button in textView1 b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"2"); } }); //to show value of this button in textView1 b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"3"); } }); //to show value of this button in textView1 b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"4"); } }); //to show value of this button in textView1 b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"5"); } }); //to show value of this button in textView1 b6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"6"); } }); //to show value of this button in textView1 b7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"7"); } }); //to show value of this button in textView1 b8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"8"); } }); //to show value of this button in textView1 b9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"9"); } }); //to show value of this button in textView1 b0.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"0"); } }); //to show value of this button in textView1 dec.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { txt1.setText(txt1.getText()+"."); } }); //To calculate Log with base 10 log10.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(log10); ans = Math.log10(var1); txt2.setText(ans.toString()); enter.setEnabled(false); buttonFalse(); } }); //To Add add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(add); buttonFalse(); addition = true; } }); //To subtract sub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(sub); buttonFalse(); subtract = true; } }); //To multiply mul.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(mul); buttonFalse(); multiply = true; } }); //To divide div.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(div); buttonFalse(); divide = true; } }); //To calculate square sq.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(sq); ans = var1 * var1; txt2.setText(ans.toString()); enter.setEnabled(false); buttonFalse(); } }); //To calculate square Root sqrt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(sqrt); ans = Math.sqrt(var1); txt2.setText(ans.toString()); enter.setEnabled(false); buttonFalse(); } }); //To calculate cube cb.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(cb); ans = var1 * var1 * var1; txt2.setText(ans.toString()); enter.setEnabled(false); buttonFalse(); } }); //To calculate Cube Root cbrt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { setVar1(); colorChange(cbrt); ans = Math.cbrt(var1); txt2.setText(ans.toString()); enter.setEnabled(false); buttonFalse(); } }); //To clear and refresh everything! clear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { allReset(); } }); //To calculate answer enter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { var2 = Double.parseDouble(txt1.getText().toString()); if(addition){ ans = var1 + var2; } else if (subtract){ ans = var1 - var2; } else if (multiply){ ans = var1 * var2; } else if (divide){ ans = var1 / var2; } else { ans = ans + 0; } txt2.setText(ans.toString()); enter.setEnabled(false); } }); } //To disable buttons public void buttonFalse(){ sub.setEnabled(false); mul.setEnabled(false); div.setEnabled(false); add.setEnabled(false); txt1.setText(""); } //To set val1 value public void setVar1(){ var1 = Double.parseDouble(txt1.getText().toString()); } //to reset all buttons and textview public void allReset(){ sq.setBackgroundColor(getResources().getColor(R.color.buttonColor)); sqrt.setBackgroundColor(getResources().getColor(R.color.buttonColor)); cb.setBackgroundColor(getResources().getColor(R.color.buttonColor)); cbrt.setBackgroundColor(getResources().getColor(R.color.buttonColor)); log10.setBackgroundColor(getResources().getColor(R.color.buttonColor)); add.setBackgroundColor(getResources().getColor(R.color.buttonColor)); mul.setBackgroundColor(getResources().getColor(R.color.buttonColor)); sub.setBackgroundColor(getResources().getColor(R.color.buttonColor)); div.setBackgroundColor(getResources().getColor(R.color.buttonColor)); enter.setEnabled(true); sub.setEnabled(true); mul.setEnabled(true); div.setEnabled(true); add.setEnabled(true); txt1.setText(""); txt2.setText(""); } //to change button color public void colorChange(Button b){ b.setBackgroundColor(getResources().getColor(R.color.colorAccent)); } }

Bước 8. Đã xong! Chạy thử ứng dụng và cho mình biết về trải nghiệm của bạn ở phía dưới nhé.

Bạn có thể tải toàn bộ source của bài hướng dẫn tại đây nhé.

DOWNLOAD CODE

Qua bài viết này, mình đã hướng dẫn chi tiết nhất có thể để tạo một ứng dụng máy tính. Mặc dù còn nhiều thiếu sót, mong bạn đọc bỏ qua và tiếp tục ủng hộ tác giả nhé.

Đọc thêm cái bài hướng dẫn tạo app android đầy đủ:

  • Sử dụng Android SoundPool xây dựng Piano App
  • Cách tạo Chat Head như Facebook Messenger
  • Xây dựng ứng dụng Android chuyển đổi video sang GIF

Cách dụng Calculator trên Android

​Đăng kí nhận sách ​dạy ​kiếm tiền từ ứng dụng di động

​Bạn đã bao giờ tự hỏi Hà Đông kiếm tiền tỷ từ ​Flappy Bird như nào không? ​Bạn biết cách lập trình nhưng lại không biết làm sao để kiếm được tiền từ nó?

Hiện cuốn sách đang bán rất chạy trên Amazon với giá 9.99$. Bạn có muốn nhận cuốn sách này để học kiếm tiền không? ​Đăng kí để nhận miễn phí nhé

DOWNLOAD

Cách dụng Calculator trên Android