안드로이드 기본

2021. 1. 8. 02:52kotlin-이론

안드로이드 기본 

java -> com -> example -> app 이름 이렇게 진행되고 있다. 하지만 IDE에서는 편하게 바로 볼 수 있게 만들어주고 있다. 

 

 

MainActivity 

 

처음 시작하면 만들어지는 kotlin 파일 제일 첫화면이다. 

 

MainActivity.xml

프로젝트가 처음 만들어지면 생기는 xml 파일이다. xml 파일에는 일반적으로 뷰가 어떤 UI로 보여야 하는가에 대한 정보가 들어있다. 글자 크기, 폰트, 색, 위치 등등

xml 파일

manifest.xml

1. 각종 권한 

카메라, 인터넷, 전화 등등의 각종 권한이 필요하다. 옛날에는~~ manifest로만 충분했지만 이젠 코드로도 권한을 요청해주어야한다.

 

2. activity 정보가 있음

Inflater 정보가 있으면 처음 앱을 시작할 때 해당 activity가 시작함

 

Gradle

그래들은 build tool이다. 안드로이드 스튜디오의 경우 코드를 편집하기만 하지 빌드 시스템과는 완전히 별개이다. 따라서 안드로이드 프로젝트 안에 Gradle 이라는 build tool이 필요하다.

build.gradle(Project: My_Application)

1. 프로젝트를 만드는데 필요한 모듈에 대한 설정 들이 있다.

2. 모든 안드로이드 프로젝트는 build.gradle을 갖고 있다.

3. build.gradle에 대한 의존성도 들어있다.

 

build.gradle(Module: app)

1. 프로젝트 레벨에 build.gradle을 추가하기 위해 각 모듈은 build.gradle을 자신의 것으로 갖고 있어야한다.

2. 각 모듈에 대한 설정을 할 수 있다.

3. 빌드 레벨을 수정하는데 가장 많이 변화시키는 파일 중 하나이다.

 

AppCompatActivity

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

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

 

AppCompatActivity는 Activity의 subclass로 현대적인 안드로이드 특징들을 제공하고 있다. 

 

Activity는 초기화 해주기 위해 생성자를 사용해주지 않는다. 그래서 속히 lifecycle이라고 불리는 method를 통해 초기화를 진행한다. OnCreate를 통해 초기화를 진행하고 항상 override 해주어야한다.

 

xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

가로와 세러 사이즈는 layout_width, layout_height를 사용한다. 

 

wrap_content: 내용물의 사이즈 만큼 크기가 지정된다. 

match_parent: 부모의 크기를 그대로 가져온다. 

 

 

버튼 생성

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/roll_label" />

 

text -> string으로 변경하는 법 마우스를 위치 시키고 mac 기준 control + Enter, window 기준 Alt + Enter

 

Linear Layout 

 

세로 정렬로 변경

android:orientation="vertical"

 

각 오브젝트를 가운데로 정렬 

 

가로 기준으로 가운데 위치

android:layout_gravity="center_horizontal"

 

세로 기준으로 가운데 위치

android:layout_gravity="center_vertical"

 

Button 클릭 기능 합쳐서 roll Dice 해주기

package com.example.myapplication

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

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()
        }
    }

    private fun rollDice(){
        Toast.makeText(this, "button clicked",
            Toast.LENGTH_SHORT).show()
    }
}

 

버튼 클릭할 때 마다 text 바꿔주기

private fun rollDice(){
        val resultText: TextView = findViewById(R.id.result_text)
        val randomInt = (1..6).random()
        resultText.text = randomInt.toString()
    }

 

xml 형태의 이미지 drawable에 저장

 

버튼 클릭시 이미지 변경으로 변화

 

 private fun rollDice(){
        val randomInt = (1..6).random()
        val diceImage: ImageView = findViewById(R.id.dice_image)

        val drawableResource = when (randomInt) {
            1 -> R.drawable.dice_1
            2 -> R.drawable.dice_2
            3 -> R.drawable.dice_3
            4 -> R.drawable.dice_4
            5 -> R.drawable.dice_5
            else -> R.drawable.dice_6
        }

        diceImage.setImageResource(drawableResource)
    }

 

효율적이게 변화

 

계속 앱을 실행하다 보면 몇번 느리게 진행되거나 주사위가 안보일 수 있다. 이는 위의 코드에서 버튼 클리이 진행될 때 마다 findViewById를 통해 dice_image라는 id의 엘리먼트를 찾아가기 때문이다. 

var diceImage : ImageView? = null

위와 같이 변화시켜도 될것 같지만 activity에서는 생성자를 사용해주지 않기 때문에 객체를 할당해주기 힘들다. 따라서 lateInit를 사용해주면 된다. 

 

lateInit의 경우 나중에 인스턴스화 해주어도 된다. 따라서 nullPointException도 피할 수 있어서 문제없이 실행할 수 있다. 

 

 

안드로이드 초기 이미지 설정해주기 

 

안드로이드의 초기 이미지를 설정해주기 위해 android:src, tool:src 등을 사용한다. 두가지에는 차이점이 있는데 android:src의 경우 앱이 실행되었을  때 보이는 이미지 tool:src의 경우 안드로이드 스튜디오에서 보이는 화면이다.

<ImageView
        android:id="@+id/dice_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:src="@drawable/empty_dice"
        tools:src="@drawable/empty_dice"/>

 

 

Explore API levels

android {
   compileSdkVersion 28
   defaultConfig {
       applicationId "com.example.android.diceroller"
       minSdkVersion 19
       targetSdkVersion 28
       versionCode 1
       versionName "1.0"
   }

 

minSDK의 경우 최소 안드로이드 적응 버전, targetSdkVersion은 최고 안드로이드 버전이다. compileSdkVersion의 경우에는 현재 컴파일 하는 버전을 의미한다. 28의 경우에는 안드로이드 9 Pie, 19의 경우에는 4.4 kitkat이다. 

 

androidx

안드로이드x의 경우 jetpack에서 제공하는 라이브러리로 자동으로 업데이트가 지원된다. 또한 이전 버전과의 호환성을 제공합니다. 

import androidx.appcompat.app.AppCompatActivity

 

 

androidx로 import를 시작한다. 

 

외부 라이브러리 추가하기

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}

 

github에 가보면 

dependencies {
    def room_version = "2.2.5"

    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.prolificinteractive:material-calendarview:1.4.3'
}