이번 강좌에서는 MainActivity, 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"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="7dp" android:onClick="onClick" android:id="@+id/btnStart" android:text="Start" tools:ignore="MissingConstraints" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_gravity="center" android:layout_margin="25dp" android:id="@+id/MainText"/> </LinearLayout>
코틀린은 NULL을 구분하기 위해서'?'를 사용합니다.
즉 변수 뒤에'?' 가 있을 경우 NULL을 허용한다는 뜻입니다
'?'가 없을 경우는 NULL을 허용할 수 없어 컴파일이 안됩니다.
when문은 자바에서 사용하는 switch 문과 동일합니다.
버튼에 설정한 onClick를 연결하기 위해서 상속된 Listener 가상 함수 onClick을 override 합니다.
onClick 함수에서는 코틀린 when을 사용해서 버튼 ID를 구분해서 텍스트 뷰를 변경하는 로직을 추가합니다.
override fun onClick(v: View?) {
when(v?.id)
{
R.id.btnStart->{
var tView = findViewById<TextView>(R.id.MainText)
if( bCheck) {
tView.setText("Click Button")
bCheck = false
}
else
{
tView.setText("Hello World!")
bCheck = true
}
}
}
}
댓글
댓글 쓰기