woong's

Android Kotlin 사용하기 본문

Develop/Android

Android Kotlin 사용하기

dlsdnd345 2016. 3. 10. 11:15
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android Kotlin 사용하기


안녕하세요. 최근에 Android Java 소송이 발생한후 대체 언어에 대해 관심이 많은데..

kotlin 이 얘기가 많이 나오고 있는것 같습니다. JetBrain 사에서 만든 Android Studio Plugin 으로

제공이 되어서 접근이 용이해서 많은 여러 개발자 분들이 선행 작업을 하고 계시고 있는것 같습니다.

저 또한 뒤늦게 남아 설치 작업 및 맛 보기 코드를 작성해 보려 합니다.


아래 커니님의 블로그를 참고

http://kunny.github.io/lecture/kotlin/2016/03/08/android_with_kotlin_part_1/


설치 및 사전 작업 


Android Preferences < Plugins < Install JetBrains Plugin < Kotlin 검색 < Install

위와 같이 설치를 진행하면 재시작이 되고 설치가 완료 됩니다.







설치가 완료 되고 재시작이 되었으면 build.gradle 의 프로젝트 설정을 해야 합니다.

루트에 존재하는 build.gradle 에 kotlin 를 불러올 저장소를 명시 해야 합니다. 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Top-level build file where you can add configuration options common to all sub-projects/modules.
 
buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.5.0'
        classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
 
allprojects {
    repositories {
        jcenter()
    }
}
 
task clean(type: Delete) {
    delete rootProject.buildDir
}
cs



mavenCentral() 을 추가하고 kotlin classPath 를 추가합니다.



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
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' // 플러그인 추가
 
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
 
    defaultConfig {
        applicationId "com.android.woong.kotlin"
        minSdkVersion 18
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
 
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin' // src/main/kotlin 디렉터리 추가
    }
}
 
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'org.jetbrains.kotlin:kotlin-stdlib:+' // 라이브러리 추가
}
cs


상단에 플러그인을 추가 , 해당 디렉토리 설정 , 라이브러리 추가 작업을 진행 합니다.

이제 프로젝트 설정이 완료되어서 kotlin 코드를 혼용해서 사용 할수 있습니다.



src/main/kotlin 폴더를 생성하면 파란색으로 변경되는것을 보실수 있습니다.

설정이 제대로 이루어져야 파란색으로 변경 됩니다. 패키지를 추가하고 코틀린 파일을 생성해서

코드를 작성합니다. 


1
2
3
4
5
6
7
package com.android.woong.kotlin
 
/**
 * Created by woong on 2016. 3. 10..
 */
 
fun sayHello(name : String) : String = "Hello , $name";
cs


간단한 메서드 함수를 작성해 보았습니다. 최근 아이폰도 같이 하고 있는데 스위프트 문법과 비슷합니다.

kotlin 1.0 발표때 자료를 보니 스위프트와 거의 스타일이 비슷하다고 소개도 되었던것 같습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MainActivity extends AppCompatActivity {
 
    TextView text;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        text = (TextView) findViewById(R.id.text);
        text.setText(HelloKt.sayHello("woong"));
    }
 
}
cs

위와 같이 Hellokt , 함수를 호출하면 불러와 지는것을 볼수 있습니다.




결론

현재 많은 여러 개발자 분들이 kotlin 을시도 해보고 있는것 같습니다. 아이폰의 스위프트 처럼 이용이 될지
는 앞으로 두고 봐야 할것 같습니다. 그럴 경우를 대비해서 조금씩 학습을 해보는 것도 좋을것 같습니다.
한번에 몰아서 하려면 일이 되버리고 학습면에서 습득하는데도 더욱 힘들기 때문에 쉽지 않겠지만 틈틈히 공부해야 될것
같습니다. 




Comments