Android Application

Kotlin 함수

작성자 임베디드코리아 작성일23-08-27 20:38 조회1,711회 댓글0건

첨부파일

----------------------------------------------------------------------------------------
    MainActivity..kt
----------------------------------------------------------------------------------------
class MainActivity : AppCompatActivity() {
    private lateinit var text1: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //텍스트뷰 초기화
        text1 = findViewById(R.id.textView)
        //text1 = findViewById<TextView>(R.id.textView);

        // print Function
        printSum(5104, 1005)
        printString("Embedded Korea")

        var tot = sumFun(10, 20)
        text1.append("return 값 \n")
        text1.append("sum + 100 = $tot \n")

        // 단일 표현식 함수
        text1.append("\n단일 표현식 함수 \n")
        var s1=sum(30,60)
        text1.append("return 값 : $s1 \n")

        var s2=sum(30,220)
        text1.append("return 값 :  $s2 \n")

    }

    fun printSum(a: Int, b: Int): Unit {
        text1.append("------- printSum -------\n")
        text1.append("sum of $a and $b is ${a + b}\n")
        text1.append("\n")
    }

    fun printString(s: String){
        text1.append("--- printString ---Unit 생략---\n")
        text1.append("$s\n")
        text1.append("\n")
    }

    fun sumFun(a: Int, b: Int): Int {

        var sum : Int

        sum = a + b
        text1.append("** 함수 내에서 출력 ** \n")
        text1.append("$a + $b = $sum \n")
        return sum+100
    }

    fun sum(a: Int, b: Int): Int {
        return a + b
    }

    fun sum2(a: Int, b: Int) = a + b
}

----------------------------------------------------------------------------------------
    activity_main.xml
----------------------------------------------------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>