IT/Android

[Android Kotlin Fundamentals 따라하기] 01.2: Anatomy of Basic Android Project (Dice Roller)

GeunChoi 2020. 10. 26. 10:26
728x90

android 2.0 버전 때 java로 안드로이드 앱 개발을 해본적이 있었는데, 요새 다시 앱개발이 해보고 싶어졌다.

 

안드로이드 공식 언어인 Kotlin으로 개발을 해보려고 이리저리 찾아보았다.

 

온라인 CodeLab을 지원해줘서 하나씩 따라해보면서 Android Kotlin 앱 개발을 시작해보려고 한다.

 

 

아래 링크에서 Lesson1 부터 시작하면 된다.

https://developer.android.com/courses/kotlin-android-fundamentals/overview

 

Android Kotlin Fundamentals  |  Training Courses  |  Android Developers

The Android Kotlin Fundamentals course was created by the Google Developers Training team. In the course, you learn Android Kotlin programming concepts and build a variety of apps. The Android Kotlin Fundamentals course materials include: Prerequisites Thi

developer.android.com

 

개발 툴은 안드로이드 스튜디오를 사용한다.

(아래는 다운로드 링크)

https://developer.android.com/studio/

 

Download Android Studio and SDK tools  |  Android 스튜디오

developer.android.com

 

 

Install Android Studio, Get started 챕터는

 

안드로이드 스튜디오 다운로드, 애뮬레이터를 생성, 프로젝트 생성하는 방법인데

 

따라해보면 쉽게 할 수 있다.

(그림으로 상세하게 설명되어 있음)

 

실질적인 실습은 01.2 챕터부터다.

 

 

앱 실행 버튼

안드로이드 스튜디오 UI가 익숙치 않아서 실행하는데 헤매었다.

 

해당 버튼을 클릭하면 앱이 실행되는데 애뮬레이터(가상머신)이 실행되어 있지 않다면 

 

가상머신 실행후에 앱을 실행한다.

 

실행결과

Kotlin으로 처음만들어 본 DiceRoller 앱 ROLL 버튼을 누르면 랜덤으로 주사위 값을  표시해주는 간단한 기능을 가진 앱이다.

 

 

Kotlin은 처음 접해보는 언어라서 변수를 지정하는 선언문에서 좀 헷갈린게 있었는데, 

 

예제에서는 val 키워드로만 변수들이 선언되어 있었다. 

 

예제 이외의 기능을 추가하는 Coding Challenge에서는 변수에 값을 할당해서 구현해야 하는데, 

 

값이 할당이 안되서 찾아보니 변수 선언에는 val/var 두가지 키워드가 있었다.

val/var 키워드의 차이점

val로 선언된 변수는 읽기만 가능하고, var로 선언된 변수는 읽기/쓰기가 가능하다.

 

Code Lab에 있는 예제에 COUNT UP이라는 기능을 추가해보았다.

 

아래는 COUNT UP 기능에 대한 조건이다.

- "COUNT UP" 버튼을 ROLL 버튼 아래에 추가, 클릭시 숫자를 1씩 증가
- result text가 default로 "Hello Wolrd"일 경우 result text에 1을 할당
- 숫자가 6이라면, 숫자 증가는 이루어 지지 않음
실행결과

COUNT UP 기능을 추가 구현한 DiceRoller 앱 

 

아래는 COUNT UP 추가 기능까지 구현한 소스코드이다.

 

소스코드
MainActivity.kt
package com.example.android.diceroller

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

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

        val rollButton: Button = findViewById(R.id.roll_button);
        rollButton.setOnClickListener{ rollDice() }; //roll_button 버튼에 onclick 이벤트 할당

        val countUpButton: Button = findViewById(R.id.count_up);
        countUpButton.setOnClickListener{ countUp() }; //count_up 버튼에 onclick 이벤트 할당

        //result text가 Default로 String일 경우 result text에 1을 할당
        val resultText: TextView = findViewById(R.id.result_text);
        var text = resultText.toString().toIntOrNull(); //Int형이 아니면 Null
        if(text == null) resultText.text = "1";
    }

    private fun rollDice(){
        val resultText: TextView = findViewById(R.id.result_text);
        val randomInt = (1..6).random(); //1~6 랜덤함수
        resultText.text = randomInt.toString();
    }

    private fun countUp(){
        val resultText: TextView = findViewById(R.id.result_text);
        var num =  resultText.text.toString().toInt();
        if(num != 6) num += 1;
        resultText.text = num.toString();

    }
}
소스코드
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_gravity="center_vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/result_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:text="Hello World!" />
    <Button
        android:id="@+id/roll_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/roll_label">

    </Button>

    <Button
        android:id="@+id/count_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/count_up_label">

    </Button>
</LinearLayout>
소스코드
strings.xml
<resources>
    <string name="app_name">DiceRoller</string>
    <string name="roll_label">Roll</string>
    <string name="count_up_label">Count Up</string>
</resources>