ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 14.[Android] activity간 데이터 전달 (계산기)
    Android 2019. 10. 13. 19:34
    반응형

    간단한 계산이 가능한 계산기를 만들어보면서 activity 간 데이터 전달 방법을 학습해보겠습니다.

     

    사용할 방법은 startActivityForResult를 사용하여 MainActivity에서 SubActivity에 어떤 연산자를 사용할 건지 데이터를 보내고

    SubActivity에서 연산할 숫자를 입력한 뒤 MainActivity에 연산한 값을 출력하게 만들겠습니다.

     

     

     

     

    1. activity_main.xml

    <?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">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center">
    
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="연산자를 선택해 주세요"
                android:textSize="30dp"
                android:textStyle="bold" />
    
        </LinearLayout>
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
    
            <TextView
                android:id="@+id/bt_plus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:background="@drawable/bg_custom_button"
                android:gravity="center"
                android:text="+"
                android:textColor="@android:color/white"
                android:textSize="30dp"
                android:textStyle="bold" />
    
            <TextView
                android:id="@+id/bt_minus"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:background="@drawable/bg_custom_button"
                android:gravity="center"
                android:text="-"
                android:textColor="@android:color/white"
                android:textSize="30dp"
                android:textStyle="bold" />
    
            <TextView
                android:id="@+id/bt_multiplication"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:background="@drawable/bg_custom_button"
                android:gravity="center"
                android:text="*"
                android:textColor="@android:color/white"
                android:textSize="30dp"
                android:textStyle="bold" />
    
            <TextView
                android:id="@+id/bt_division"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:background="@drawable/bg_custom_button"
                android:gravity="center"
                android:text="/"
                android:textColor="@android:color/white"
                android:textSize="30dp"
                android:textStyle="bold" />
        </LinearLayout>
    
        <TextView
            android:id="@+id/tv_return"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:textSize="30dp"
            android:textStyle="bold" />
    </LinearLayout>
    
    

    2.activity_sub

    <?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=".SubActivity">
    
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <EditText
                android:id="@+id/et_first"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />
    
            <EditText
                android:id="@+id/et_second"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1" />
        </LinearLayout>
    
        <TextView
            android:id="@+id/bt_send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:background="@drawable/bg_custom_button"
            android:gravity="center"
            android:text="연산"
            android:textColor="@android:color/white"
            android:textSize="30dp"
            android:textStyle="bold" />
    </LinearLayout>

     

    일단 위에 처럼 본인이 원하는 대로 레이아웃을 만듭니다.

     

    3.MainActivity

    package com.cnm.intentstudy
    
    import android.app.Activity
    import android.content.Intent
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import kotlinx.android.synthetic.main.activity_main.*
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            val intent = Intent(this, SubActivity::class.java)
            
    //        1 -> + , 2 -> - , 3 -> * , 4 -> /
            bt_plus.setOnClickListener {
                intentLoad(intent, "1")
            }
            bt_minus.setOnClickListener {
                intentLoad(intent, "2")
            }
            bt_multiplication.setOnClickListener {
                intentLoad(intent, "3")
            }
            bt_division.setOnClickListener {
                intentLoad(intent, "4")
            }
    
        }
    
    //    연산자를 구분할 수 있는 값을 intent에 저장하고 SubActivity에 넘겨주는 함수
        private fun intentLoad(intent: Intent, value: String) {
            intent.putExtra("cal", value)
            startActivityForResult(intent, 1001)
    
        }
    
    //    SubActivity에서 연산 값을 받아와서 결과값을 출력해준다.
        override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
            if (requestCode == 1001) {
                if (resultCode == Activity.RESULT_OK) {
                    tv_return.text = data?.getStringExtra("result")
                }
            }
        }
    }
    

     

    4.SubActivity

    package com.cnm.intentstudy
    
    import android.app.Activity
    import android.content.Intent
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import kotlinx.android.synthetic.main.activity_sub.*
    
    class SubActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_sub)
    
            bt_send.setOnClickListener {
    //            연산 할 값이 둘 중 하나라도 입력이 안되있으면 Toast로 알려주고 return 한다.
                if (et_first.text.toString() == "" || et_second.text.toString() == "") {
                    Toast.makeText(this, "연산할 값을 넣어주세요.", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }
                // 연산 할 값을 저장할 변수
                val first = et_first.text.toString().toInt()
                val second = et_second.text.toString().toInt()
                
    //            intent에서 MainActivity에서 저장했던 연산자구분 값을 가져와서 연산한다음 result에 정의한다.
                val result = when (intent.getStringExtra("cal")) {
                    "1" -> {
                        "연산결과: ${first + second}"
                    }
                    "2" -> {
                        "연산결과: ${first - second}"
                    }
                    "3" -> {
                        "연산결과: ${first * second}"
                    }
                    "4" -> {
                        "연산결과: ${(first / second.toDouble())}"
                    }
                    else -> {
                        error("")
                    }
                }
    //            정의한 result값을 다시 MainActivity에 보낸다.
                val intent = Intent()
                intent.putExtra("result", result)
                setResult(Activity.RESULT_OK, intent)
                finish()
            }
    
        }
    
    
    }
    
    • Intent() -> 인자로 Context와 Class를 받습니다. 보통 Context는 자기 자신인 this와 Class는 화면 전환할 Activity를 넣습니다.

     

    • intent.putExtra -> 인자로 Key와 Value를 받습니다. Key 값은 String으로 입력하여 나중에 값을 불러올 때 쓰입니다. Value는 저장할 값의 타입으로 입력합니다.

     

    • startActivityForResult() -> 다른 Activity에서 data를 받아와야 할 때 사용합니다. 인자로 intent와 임의로 정의한 requestCode를 넣어줍니다.

     

    • onActivityResult() -> 다른 Activity에서 data를 보냈을 때 받아온 Code와 data를 처리하는 함수입니다.

     

    • setResult() -> intent와 resultCode를 보냅니다.

     

    • getStringExtra -> intent에 저장한 데이터를 key으로 구분하여 가져옵니다.

     

    • resultCode
    결과값 코드 의미
    RESULT_OK 수행한 작업이 성공적일때 일반적으로 쓰는 코드
    RESULT_CANCELED 수행한 작업이 실패일때 일반적으로 쓰는 코드
    RESULT_FIRST_USER 사용자 정의 결과 코드 
    ex)
    Const val CODE : Int = Activity.RESULT_FIRST_USER +1;

     

     

     

     

    반응형

    댓글

Designed by Tistory.