포스팅 OS : Mac

검색어 : 안드로이드(Android), 코틀린(Kotlin), 텍스트뷰(TextView), 버튼(Button)




▶︎ 이전 포스팅 목록

2018/02/10 - [Android_Kotlin] - [Android Kotlin] 안드로이드 스튜디오(Andorid Studio)에 코틀린(Kotlin) 개발환경 셋팅



이전 포스팅에서는 안드로이드 스튜디오에 코틀린 개발환경을 셋팅하는 방법에 대해 알아보았습니다. 오늘은 텍스트뷰와 버튼의 기본적인 사용법에 대해 알아보려고 합니다. 개발환경 셋팅 후 처음으로 만들어보는 Hellow Kotlin 예제라고 생각하시면 됩니다.


참고로 앞으로 기본적인 설명은 왠만하면 주석으로 대체할 생각이며 안드로이드 코틀린 포스팅의 경우 자바를 어느정도 이해하시고 있다고 가정하고 진행합니다.


1. 레이아웃


<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="com.kotlin_test.Activity.HellowWorldActivity">

<TextView
android:id="@+id/txtHellow"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20dp"
android:textStyle="bold"
android:gravity="center"/>

<Button
android:id="@+id/btn_clear"
android:text="Text Clear"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_print_01"
android:text="print_01"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:id="@+id/btn_print_02"
android:text="print_02"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_print_03"
android:text="print_03"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>







2. 소스


import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.kotlin_test.R
import kotlinx.android.synthetic.main.activity_hellow_world.*

class HellowWorldActivity : AppCompatActivity() {

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

btn_clear.setOnClickListener {
txtHellow.setText("")
}

btn_print_01.setOnClickListener {
txtHellow.setText("Hellow Kotlin_01")
}

// val 변수 사용
btn_print_02.setOnClickListener {
// 변경 불가능한 변수 - val
// 자바로 말하면 final
val nameStr : String = "Kotlin_02"
txtHellow.setText("Hellow $nameStr")
}

// var 변수 사용
btn_print_03.setOnClickListener {
// 변경 가능한 변수 - var
var nameStr : String = "Test"
nameStr = "Kotlin_03"
txtHellow.setText("Hellow $nameStr")
}

}
}


위 소스를 보시면 자바와는 다른점이 확연히 느껴지실 겁니다. 달라진 점에 대해서는 차근차근 차후 포스팅에서 설명하겠지만 현재 눈에 보이는 가장 큰 차이는 코틀린은 데이터바인딩을 지원해서 레이아웃에 있는 뷰를  findViewById 할 필요가 없이 바로 id로 호출하여 사용이 가능하다는 점입니다.




3. 실행 결과






+ Recent posts