포스팅 OS : Mac

검색어 : 코틀린(Kotlin), 클래스(Class), 프로퍼티(Property), 커스텀 접근자, 라디오 버튼(Radio Button)



▶︎ 이전 포스팅 목록

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

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 텍스트뷰(TextView)와 버튼(Button)을 사용한 헬로 코틀린

2018/03/14 - [Android_Kotlin] - [Android Kotlin] 함수와 변수를 이용하여 에디트텍스트(EditText)에 입력한 값 중 큰 값 구하기

2018/03/15 - [Android_Kotlin] - [Android Kotlin] 문자열 템플릿(String Template) 사용법




2달만에 다시 글을 쓰게 되네요. 제가 투입된 프로젝트가 바빠져서 한동안 블로그엔 신경을 못썼습니다. 이제 좀 상황이 정리되어 다시 열심히 달려보려 합니다! 





오늘 포스팅할 주제는 코틀린의 클래스와 프로퍼티 입니다. 역시 제 포스팅 스타일대로 안드로이드 예제로 설명하려 합니다. 



우선 액티비티 하나를 만들어서 두 개의 예제로 진행하려 합니다. 

예제에 대해 간단히 설명드리면,

첫 번째 예제는 Person 이라는 객체를 생성하여 이름과 결혼 여부를 저장하고 저장된 값을 텍스트 뷰에 출력해줍니다.

두 번째 예제는 Rectangle 이라는 객체를 생성하여 가로 세로의 길이를 입력하여 저장하고 커스텀 접근자를 사용하여 정사각형 여부를 텍스트 뷰에 출력해줍니다.


늘 그렇듯 아래 소스에 주석으로 설명을 달아 놓았으니 소스 보시고 직접 실행해보시면서 이해하시면 간단합니다.

이전 포스팅에서 다뤘던 내용은 주석으로 달지 않고 최대한 소스에 적용해서 작성했습니다. 이해가 안가시는 부분은 이전 포스팅에서 찾아서 보시길 바랍니다.



1. Person 클래스

class Person(
/*
프로퍼티 생성 - 필드(변수), 접근자(Getter, Setter)를 한데 묶어 프로퍼티라 합니다.
자바와는 다르게 코틀린에서 프로퍼티 생성 시 Getter, Setter등의 접근자를 따로 생성해줄 필요가 없습니다.

ex) 코틀린으로 생성된 Person을 자바로 생성했을 경우 소스 예제입니다.
public class Person {
private final String name;
private boolean isMarried;

public Person(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setMarried(boolean married) {
isMarried = married;
}

public boolean isMarried() {
return isMarried;
}
}

위 처럼 긴 소스를 코틀린은 아래와 현재 이 클래스와 같이 간단하게 생성이 가능합니다.
*/

// val - 읽기 전용 프로퍼티
// var - 읽기, 쓰기 전용 프로퍼티
val name: String,
var isMarried : Boolean = false
)




2. Rectangle 클래스

class Rectangle (val height : Int, val width : Int) {
// 커스텀 접근자 생성
val isSquare : Boolean
/* // 블록을 본문으로 사용하는 방법
get() {
return height == width
}
*/
// 식을 본문으로 사용하는 방법
get() = height == width
}



3. 레이아웃

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

<TextView
android:text="1. Person"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#0054FF"
android:gravity="center"/>
<EditText
android:id="@+id/edt_person_nm"
android:hint="이름을 입력하세요"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20sp"
android:gravity="center"
android:background="@null"/>

<RadioGroup
android:id="@+id/rdo_married"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<RadioButton
android:id="@+id/rbtn_married_false"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="미혼"
android:paddingRight="20dp"/>
<RadioButton
android:id="@+id/rbtn_married_true"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="기혼" />
</RadioGroup>

<Button
android:id="@+id/btn_person_save"
android:text="저장"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_person_print"
android:text="출력"
android:layout_width="match_parent"
android:layout_height="50dp" />

<TextView
android:id="@+id/txt_person_result"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textSize="20sp"
android:gravity="center"/>


<TextView
android:text="2. Rectangle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:textSize="20sp"
android:textStyle="bold"
android:textColor="#0054FF"
android:gravity="center"/>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:weightSum="4">
<EditText
android:id="@+id/edt_width"
android:hint="가로 길이"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:background="@null"
android:inputType="number"
android:gravity="center"/>
<EditText
android:id="@+id/edt_height"
android:hint="세로 길이"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="2"
android:background="@null"
android:inputType="number"
android:gravity="center"/>
</LinearLayout>

<Button
android:id="@+id/btn_rect_save"
android:text="저장"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_rect_print"
android:text="정사각형 여부 판독"
android:layout_width="match_parent"
android:layout_height="50dp" />

<TextView
android:id="@+id/txt_rect_result"
android:layout_width="match_parent"
android:layout_height="80dp"
android:textSize="20sp"
android:gravity="center"/>

</LinearLayout>



4. 액티비티 소스

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.kotlin_test.R
import com.kotlintest.model.Person
import com.kotlintest.model.Rectangle
import kotlinx.android.synthetic.main.activity_property.*

class PropertyActivity : AppCompatActivity() {

private var person : Person? = null
private var isMarried : Boolean = false

private var rect : Rectangle? = null

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

// ---------------
// 1. Person
// ---------------
// 결혼 유무 선택
rdo_married.setOnCheckedChangeListener { radioGroup, i -> if(i == R.id.rbtn_married_true) isMarried = true else isMarried = false}

// 저장
btn_person_save.setOnClickListener {
person = Person(edt_person_nm.text.toString(), isMarried)
txt_person_result.setText("저장 완료!")
}

// 출력
btn_person_print.setOnClickListener {
val stringMarried : String = if(person != null) person?.isMarried.toString() else "false"
val marriedYn : Boolean

if ( stringMarried.equals("true"))
marriedYn = true
else
marriedYn = false

txt_person_result.setText("이름 : ${person?.name}\n결혼유무 : ${if(marriedYn) "기혼" else "미혼" }")
}

// ---------------
// 2. Rectangle
// ---------------
// 저장
btn_rect_save.setOnClickListener {
rect = Rectangle(Integer.parseInt(edt_height.text.toString()), Integer.parseInt(edt_width.text.toString()))
txt_rect_result.setText("저장 완료!")
}

// 정사각형 여부 판독
btn_rect_print.setOnClickListener {
val stringSquare : String = if(rect != null) rect?.isSquare.toString() else "false"
val isSquare : Boolean
if(stringSquare.equals("true")) isSquare = true else isSquare = false

if(isSquare) txt_rect_result.setText("정사각형") else txt_rect_result.setText("직사각형")
}
}
}



5. 실행 결과





이번 포스팅을 직접 테스트해보시면 코틀린에서 자바대비 얼마나 소스의 양을 줄일 수 있을지 가늠하실 수 있을 것 같네요. 



+ Recent posts