Skip to content

Latest commit

Β 

History

History
74 lines (52 loc) Β· 2.77 KB

AndroidKTX.md

File metadata and controls

74 lines (52 loc) Β· 2.77 KB

Android Kotiln Extensions 와 Anko

1. Android KTX

μš”λ²ˆ Google I/O 2018 μ—μ„œ λ°œν‘œν•œ Android Jetpack 에 Android KTX κ°€ 포함 λ˜μ—ˆλ‹€.
Android KTX 의 λͺ©μ μ€ Kotlin의 간결함과 κΈ°λŠ₯을 ν™œμš©ν•˜μ—¬ Android κ°œλ°œμ„ 보닀 κ°„κ²°ν•˜κ³  μΎŒμ ν•˜κ³  κ΄€μš©μ μœΌλ‘œ λ§Œλ“œλŠ” 것이닀.

1-1. μ‹œμž‘ν•˜κΈ°

Android KTX λ₯Ό ν”„λ‘œμ νŠΈμ— μ‚¬μš©ν•˜κΈ° μœ„ν•΄μ„œλŠ” build.gradle νŒŒμΌμ— μ•„λž˜μ²˜λŸΌ μΆ”κ°€ ν•œλ‹€.

repositories {
    google()
}

build.gradle(Project: ν”„λ‘œμ νŠΈλͺ…) λΆ€λΆ„

dependencies {
    implementation 'androidx.core:core-ktx:1.0.0-alpha1'
}

build.gradle(Module: app) λΆ€λΆ„

import kotlinx.android.synthetic.main.<layout>.*

μœ„μ— 처럼 import ν•΄μ„œ μ‚¬μš©ν•˜μž

1-2. KTX λ₯Ό μ‚¬μš©μ‹œ μƒκΈ°λŠ” λ§ˆλ²•λ“€

자, κ·Έλ ‡λ‹€λ©΄ μ–Έμ œ μ–΄λ””μ„œ μ–΄λ–»κ²Œ KTX λ₯Ό μœ μš©ν•˜κ²Œ μ“Έ 수 μžˆμ„κΉŒ?

λŒ€ν‘œμ μΈ 예둜 기쑴에 μš°λ¦¬κ°€ 자주 μ‚¬μš©ν–ˆλ˜ findViewById() λ©”μ„œλ“œμ—μ„œ λ‚˜νƒ€λ‚œλ‹€.

findViewById() λŠ” μ•‘ν‹°λΉ„ν‹°λ‚˜ ν”„λž˜κ·Έλ¨ΌνŠΈ λ“± λ ˆμ΄μ•„μ›ƒ νŒŒμΌμ— μ„ μ–Έλœ μ—¬λŸ¬κ°œμ˜ λ·°(view)둜 κ΅¬μ„±λœ ν™”λ©΄μ—μ„œ νŠΉμ • 뷰의 μΈμŠ€ν„΄μŠ€λ₯Ό μ–»κΈ°μœ„ν•΄ μ‚¬μš©ν•œλ‹€.

κ·ΈλŸ¬λ‚˜ λ¬Έμ œμ μ€ λ§Œμ•½ 이 λ©”μ„œλ“œμ—μ„œ λ°˜ν™˜ν•œ λ·° 객체λ₯Ό 잘λͺ»λœ νƒ€μž…μ˜ 뷰둜 μΊμŠ€νŒ…ν•˜κ±°λ‚˜ λ‹€λ₯Έ λ ˆμ΄μ•„μ›ƒμ— μ„ μ–Έλœ IDλ₯Ό 잘λͺ» μ‚¬μš©ν•˜λ©΄ 널 값을 λ°˜ν™˜ν•˜κ²Œ λ˜λŠ”λ°,

μ΄λŠ” μ‹€μˆ˜λ‘œ 버그λ₯Ό λ°œμƒμ‹œν‚€κΈ° 맀우 μ‰¬μ›Œ μš°λ¦¬λ“€μ—κ²Œ 번거둭게 ν•œλ‹€.

뿐만 μ•„λ‹ˆλΌ 가독성도 μž₯λ‚œ μ•„λ‹ˆκ²Œ λ–¨μ–΄λœ¨λ¦°λ‹€.
μ™œλƒν•˜λ©΄ λ³΅μž‘ν•œ ꡬ쑰둜 κ΅¬μ„±λœ ν™”λ©΄μ—μ„œ 일일이 findViewByID() λ₯Ό λ·° μΈμŠ€ν„΄μŠ€λ₯Ό λ°›μ•„μ•Ό ν•˜κΈ° λ•Œλ¬Έμ— μ½”λ“œλ§Œ λͺ‡μ‹­ 쀄을 μ°¨μ§€ν•˜κ²Œ 되기 λ•Œλ¬Έμ΄λ‹€. (닡도 μ—†λ‹€)

μ—¬κΈ°μ„œ μ™œ findViewByID() λŒ€ν•œ λ‚˜μœ μ–˜κΈ°λ₯Ό κΊΌλ‚Έ μ΄μœ λŠ” λ¬΄μ—‡μΌκΉŒ?

λ‹Ήμ—°νžˆ Adroid KTX λŠ” 이런 뢀뢄듀을 κΉ”λ”ν•˜κ²Œ ν•΄κ²°ν•΄ μ£ΌκΈ° λ•Œλ¬Έμ΄λ‹€.

Android KTX λŠ” 뷰의 ID λ₯Ό μ‚¬μš©ν•˜μ—¬ ν•΄λ‹Ή 뷰의 μΈμŠ€ν„΄μŠ€μ— λ°”λ‘œ μ ‘κ·Ό ν•  수 있게 ν•΄μ€€λ‹€.
λ‹€μ‹œλ§ν•΄, findViewByID() λ•Œλ¬Έμ— 생긴 λͺ‡μ‹­ μ€„μ˜ μ½”λ“œλ₯Ό λΉ„μ•½μ μœΌλ‘œ 쀄일 수 μžˆλ‹€λŠ” 것이닀.

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
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)

        // findViewById() 을 μ‚¬μš©μ•ˆν•΄λ„ 뷰의 ID 에 μ ‘κ·Όν•΄ μ‚¬μš©κ°€λŠ₯ν•˜λ‹€.
        text.text = "hi"
        text.setOnClickListener{
            Toast.makeText(applicationContext, "hi", Toast.LENGTH_SHORT).show()
        }
    }
}

1-3. 더 λ‚˜μ•„κ°€κΈ°