개발자 승학

코틀린 버튼클릭 이벤트 본문

it/코틀린(Kotlin)

코틀린 버튼클릭 이벤트

유승학 2018. 5. 29. 10:38

저번 포스팅에서는 코틀린이란 무엇인가?


코틀린과 자바의 간단한 비교를 보았습니다.


이번에는 안드로이드 스튜디오와 코틀린으로 간단한 버튼과 EditText로 TextView를 변경해보겠습니다.


우선 android studio를 실행 시킵니다.


File > New Project


새로운 프로젝트를 생성합니다.


위 사진과 같이 새 프로젝트를 생성하고 빨간색 박스처럼 Inclue Kotlin support를 체크합니다.


새 프로젝트를 생성하셨다면 build.gradle을 봅니다.



위 두 사진처럼 코틀린 관련 gradle이 추가됩니다. 엄청 편리하네용!


간단하게 Button,TextView 그리고 EditText를 배치해볼게요.


[activity_main.xml]

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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/text_kotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="67dp"
android:layout_marginEnd="11dp"
android:layout_marginRight="11dp"
android:paddingLeft="160dp"
android:paddingTop="120dp"
android:text="버튼 클릭 전"
app:layout_constraintBottom_toTopOf="@+id/btn_kotlin"
app:layout_constraintEnd_toEndOf="@+id/btn_kotlin"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/et_kotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="19dp"
android:hint="텍스트를 입력하세요."
app:layout_constraintBottom_toBottomOf="@+id/text_kotlin"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/btn_kotlin"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="272dp"
android:text="코틀린 버튼"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_kotlin"
app:layout_constraintVertical_bias="0.0" />

</android.support.constraint.ConstraintLayout>


[MainActivity.kt]

package com.example.ysh.kotlinbutton

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

var et = findViewById(R.id.et_kotlin) as EditText

btn_kotlin.setOnClickListener {
var et_text: String = et.text.toString()
text_kotlin.setText("버튼 클릭 후" + et_text + "로 변경!")
}
}
}

java로 버튼클릭하는것보다 훨씬 간결하고 편리합니다.

text를 가져오는 부분이 java에서는 .getText.toString() 이지만 코틀린은 text.toString()입니다.


그리고 세미콜론(;)이 필요없습니다. 붙여도 코드가 작동하긴 합니다.



코틀린으로 간단한 버튼이벤트를 해봤습니다.

궁금하신 점은 댓글을 달아주세요.

'it > 코틀린(Kotlin)' 카테고리의 다른 글

코틀린 시작하기  (0) 2018.05.28
Comments