<?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">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<TextView
android:id="@+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<TextView
android:id="@+id/tv3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
</LinearLayout>
class MainActivity : AppCompatActivity() {
var tv1: TextView? = null // 물음표를 붙이면 null 담을 수 있다.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv1 = findViewById(R.id.tv1)
/* 동일한 로직 */
tv1?.text = "문자1"
tv1?.setText("문자1");
// 코틀린은 findviewbyid안해도된다.!!
tv2.text ="asd"
}
}
코틀린으로 구현하는 안드로이드는 자바와 다른 점이 있다.
첫번째, ?.setText() 와 ?.text가 동일하다.
두번째, 먼저 자바에서 주구장창하던 findViewById를 할 필요가 없이 바로 View의 아이디에 구현이 가능하다. 위의 코드와 같이 아이디만 있으면 바로 가능하다.
궁금하신 점은 덧글로 적어주세요.
'안드로이드' 카테고리의 다른 글
[Android Kotlin] 안드로이드 코틀린 Seek Bar (0) | 2020.03.21 |
---|---|
[Android Kotlin] 안드로이드 코틀린 Progress Bar (0) | 2020.03.21 |
[Android Kotlin] 안드로이드 코틀린 Radio Button (0) | 2020.03.21 |
[Android Kotlin] 안드로이드 코틀린 Check Box (0) | 2020.03.21 |
[Android Kotlin] 안드로이드 코틀린 Button (0) | 2020.03.21 |