Hello, Android!

05. 인텐트, 뷰 in kotlin 본문

Android

05. 인텐트, 뷰 in kotlin

lwndnjs93 2019. 3. 11. 23:40

지금까지는 자바를 이용하였지만 새로운 안드로이드의 공식 언어 코틀린에서는 어떻게 사용할까?

코틀린을 이용하여 TextView의 텍스트를 받아오고 설정해주고

EditText를 통해 입력받는 내용을 받아오고

버튼 이벤트를 통해 액티비티를 전환해보자



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:id="@+id/tv00"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="input"
        android:id="@+id/et00"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Toast"
        android:id="@+id/bt00"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:id="@+id/bt01"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="intent"
        android:id="@+id/bt02"/>
 
</LinearLayout>
cs


메인 액티비티의 XML에는 위에서부터 Textview, EditText Button 세개를 배치하였다.

우선 EditText로 사용자에게 값을 입력받고 첫번째 bt00을 누르면 토스트메시지를 보여주고

두번째 버튼 bt01을 누르면 EditText에 입력받은 값을 TextView에 출력하고

세번째 버튼 bt02를 누르면 Main2Activity로 인텐트 이동을 하도록 할것이다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
 
class MainActivity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        bt00.setOnClickListener{
            Toast.makeText(this, et00.text, Toast.LENGTH_LONG).show()
        }
 
        bt01.setOnClickListener{
            tv00.setText(et00.text)
        }
 
        bt02.setOnClickListener{
            val intent = Intent(this, Main2Activity::class.java)
            intent.putExtra("name1""ryan")
            intent.putExtra("name2""Jay-G")
            startActivity(intent)
        }
    }
}
cs


우선 코틀린 코드와 자바 코드에서 눈에 띄게 달라진 점으로는 

자바에서는 뷰의 id에 접근하기 위해 변수를 선언하고 findViewById() 를 사용하여 접근하였지만

코틀린에서는 뷰의 아이디를 직접적으로 호출이 가능하다!!


13번줄 부터 살펴보면 findViewById()없이 bt00 XML의 첫번째 버튼에 직접 접근하여 리스너를 연결하였다.

이번에는 버튼 리스너를 살펴보자

자바의 경우 bt00.setOnClickListener(new Button.setOnclickListener(){ ... }) 주절주절 코드가 장황하게 길었지만

코틀린에서는 람다를 이용하여 단순히 bt00.setOnClickListener{ ... } 으로 확 줄어들었다 setOnClickListener의 괄호 안에

버튼 클릭시 수행할 내용을 작성하면 된다


bt00에서는 Toast메시지를 출력하는데 출력하는 문자는 et00.text 즉 사용자로부터 EditText 에 입력받는 내용을

출력하게 된다

이 부분 또한 자바에서는 et00에 findViewById를 이용하여 접근한 다음 getText()를 이용하였지만

코틀린에서는 단순히 .text 를 사용하여 값을 받아온다


다음으로 두번째 버튼 bt01에서는 bt00과 동일하게 리스너를 연결하였고

여기서는 tv00아이디에 직접 접근하여 setText에 et00에서 받아온 값을 지정하였다


마지막 세번째 bt02버튼은 인텐트를 전환하는데

인텐트를 지정할때 출발하는 액티비티는 자기 자신이라 단순히 this만 적었다

도착하는곳은 Main2Activity인데 자바에서는 클래스명.class 라고 했지만

코틀린에서는 ::class.java가 되었다

지금 Main2Activity도 코틀린 이지만 .java가 붙는 이유는 아직 잘 모르겠다;;

마지막으로 putExtra와 startActivity는 자바와 동일하게 사용된다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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=".Main2Activity">
 
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, Kotlin!"
        android:id="@+id/tv00"/>
 
</android.support.constraint.ConstraintLayout>
cs


Main2Activity의 XML에는 간단하게 TextView 하나만 배치하였다

이 TextView에서는 이전 인텐트에서 받아온 값들을 출력할 것이다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main2.*
 
class Main2Activity : AppCompatActivity() {
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
 
        val intent = intent
        val name1 = intent.getStringExtra("name1")
        val name2 = intent.getStringExtra("name2")
 
        tv00.setText("Hello! " + name1 + " & Hello!" + name2)
    }
}
cs


여기서 살펴볼 부분은 인텐트를 받는 것이다

만약 자바였다면 Intent intent = new Intent() 처럼 new를 이용하여 인텐트 객체를 생성하겠지만

코틀린에서 인텐트는 심플하게 intent 만으로 끝이다!

값을 받는것또한 자바에서는 getExtra()를 통해 값을 받으면서 getString("key")처럼 두번 호출하였지만

코틀린에서는 처음부터 String을 받는다면 getStringExtra("key") 함수가 준비되어있다

boolean, char, int, float 등등 타입별로 준비가 되어있으니

일단 인텐트.get 까지만 입력하면 준비된 함수들 목록이 나온다

한번 쭉 훑어보고 타입에 맞게 필요한 함수들을 호출하여 사용하도록 하자!


이번에는 안드로이드에서 코틀린을 어떻게 이용하고 자바와 어떤점이 다른지 알아보았다

지금까지는 별 생각없이 자바를 사용하였지만

코틀린을 사용하니 일단 코드가 정말 간결해지는 효과가 있다!

하지만 아직은 너무 당황스러울 정도로 짧아졌다는 생각이 들었다


앞으로 코틀린도 공부해서 안드로이드 개발을 할때 짧고 간결하면서 코틀린 코드를 작성할수 있도록 하자!

'Android' 카테고리의 다른 글

Retrofit2를 이용한 HTTP통신  (0) 2020.05.23
안드로이드 shared preferences  (0) 2020.05.17
04. 뷰  (0) 2019.03.10
03. 인텐트 Intent  (0) 2019.03.07
02. 액티비티 Activity  (0) 2019.03.05