짱짱해커가 되고 싶은 나

04-3. 간단한 계산기 앱 본문

모바일

04-3. 간단한 계산기 앱

동로시 2021. 2. 15. 21:21

프로젝트 계획

EditText 2개 - 2개의 정수 입력

Button 5개 - 더하기, 빼기, 곱하기, 나누기 > 누르면 연산 실행

TextView 1개 -  연산 결과 빨간색으로 보여주기

 

<activity_main.xml>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="숫자1"
        android:id="@+id/num1"/>

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="숫자2"
        android:id="@+id/num2"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/btn1"
        android:id="@+id/btn1"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/btn2"
        android:id="@+id/btn2"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/btn3"
        android:id="@+id/btn3"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="@string/btn4"
        android:id="@+id/btn4"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text"
        android:textSize="30dp"
        android:textColor="#ff0000"
        android:id="@+id/textView"/>

</LinearLayout>

 

<strings.xml>

<resources>
    <string name="app_name">초간단 계산기</string>
    <string name="btn1">더하기</string>
    <string name="btn2">빼기</string>
    <string name="btn3">곱하기</string>
    <string name="btn4">나누기</string>
    <string name="text">계산 결과:</string>
</resources>

 

<MainActivity.java>

package com.example.widget;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText n1, n2;
    Button btn1, btn2,btn3, btn4;
    TextView textView;
    String num1, num2;
    Integer result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("초간단 계산기");

        n1 = (EditText)findViewById(R.id.num1);
        n2 = (EditText)findViewById(R.id.num2);
        btn1 = (Button)findViewById(R.id.btn1);
        btn2 = (Button)findViewById(R.id.btn2);
        btn3 = (Button)findViewById(R.id.btn3);
        btn4 = (Button)findViewById(R.id.btn4);
        textView = (TextView)findViewById(R.id.textView);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                result = Integer.parseInt(num1) + Integer.parseInt(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });

        btn2.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                result = Integer.parseInt(num1) - Integer.parseInt(num2);
                textView.setText("계산 결과 : " + result.toString());
                return false;
            }
        });

        btn3.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                result = Integer.parseInt(num1) * Integer.parseInt(num2);
                textView.setText("계산 결과 : " + result.toString());
                return false;
            }
        });

        btn4.setOnTouchListener(new View.OnTouchListener(){
            public boolean onTouch(View arg0, MotionEvent arg1){
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                result = Integer.parseInt(num1) / Integer.parseInt(num2);
                textView.setText("계산 결과 : " + result.toString());
                return false;
            }
        });

    }
}

이번에 onTouchListener를 처음 사용해봤다.

클릭과 다른점은 화면에 손가락이 닿기만 하면 작동하는 것이다.

따라서 손가락의 방향, 드래그 등의 행동에 맞게 이벤트를 구현할 수 있다.

 

public boolean onTouch() 에서 return은 바로 윗 줄의 코드만을 인식한다.

터치만 하고 이벤트를 종료하고 싶을 경우는 return true로 설정하면 된다.

 

어렵다 ㅠ

 

 

기능 추가

- 나머지 값 구하기

- 실수 계산하기

- 0으로 나누면 토스트 메시지 나타내고 계산x

- 값을 입력하지 않고 눌렀을 경우 오류 메시지 토스트로 나타내기

 

<MainActivity.java>

package com.example.widget;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText n1, n2;
    Button btn1, btn2,btn3, btn4, btn5;
    TextView textView;
    String num1, num2;
    Float result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("초간단 계산기");

        n1 = (EditText)findViewById(R.id.num1);
        n2 = (EditText)findViewById(R.id.num2);
        btn1 = (Button)findViewById(R.id.btn1);
        btn2 = (Button)findViewById(R.id.btn2);
        btn3 = (Button)findViewById(R.id.btn3);
        btn4 = (Button)findViewById(R.id.btn4);
        btn5 = (Button)findViewById(R.id.btn5);
        textView = (TextView)findViewById(R.id.textView);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                if(num1.trim().isEmpty() == true || num2.trim().isEmpty() == true){
                    Toast.makeText(getApplicationContext(), "[-] 값을 입력하고 누르세요", Toast.LENGTH_SHORT).show();
                    return;
                }
                result = Float.parseFloat(num1) + Float.parseFloat(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });

        btn2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                if(num1.trim().isEmpty() == true || num2.trim().isEmpty() == true){
                    Toast.makeText(getApplicationContext(), "[-] 값을 입력하고 누르세요", Toast.LENGTH_SHORT).show();
                    return;
                }
                result = Float.parseFloat(num1) - Float.parseFloat(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });

        btn3.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                if(num1.trim().isEmpty() == true || num2.trim().isEmpty() == true){
                    Toast.makeText(getApplicationContext(), "[-] 값을 입력하고 누르세요", Toast.LENGTH_SHORT).show();
                    return;
                }
                result = Float.parseFloat(num1) * Float.parseFloat(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });

        btn4.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                if(num1.trim().isEmpty() == true || num2.trim().isEmpty() == true){
                    Toast.makeText(getApplicationContext(), "[-] 값을 입력하고 누르세요", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if(num2.equals("0")){
                    Toast.makeText(getApplicationContext(), "[-] 0으로 나누기 금지", Toast.LENGTH_SHORT).show();
                    return;
                }
                result = Float.parseFloat(num1) / Float.parseFloat(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });

        btn5.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                num1 = n1.getText().toString();
                num2 = n2.getText().toString();
                if(num1.trim().isEmpty() == true || num2.trim().isEmpty() == true){
                    Toast.makeText(getApplicationContext(), "[-] 값을 입력하고 누르세요", Toast.LENGTH_SHORT).show();
                    return;
                }
                else if(num2.equals("0")){
                    Toast.makeText(getApplicationContext(), "[-] 0으로 나누기 금지", Toast.LENGTH_SHORT).show();
                    return;
                }
                result = Float.parseFloat(num1) % Float.parseFloat(num2);
                textView.setText("계산 결과 : " + result.toString());
            }
        });


    }
}

 

'모바일' 카테고리의 다른 글

04-5. 위젯3  (0) 2021.02.16
04-4. 위젯2  (0) 2021.02.16
04-2. 위젯  (0) 2021.02.15
04-1. View  (0) 2021.02.15
03. Java 정리  (0) 2021.02.15
Comments