여러가지 방식의 Random값 가져오기

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.random/

 

kotlin.random - Kotlin Programming Language

 

kotlinlang.org

랜덤함수는 seed값으로 시간을 이용한다(nano)

https://currentmillis.com/

 

Current Millis

Convert milliseconds to date-time. Link to a moment.

currentmillis.com

1. List 활용하여 1 ~ 45 까지 번호 가져오기 

import java.util.Random

// mutableListOf: 수정가능한 Lits

fun main() {
    var random = Random()
    var list = mutableListOf<Int>()
    while(list.size < 6){
        val randomNumber = random.nextInt(45) + 1
        if(list.contains(randomNumber)){
            continue
        }
        list.add(randomNumber)
    }
    print(list)
}

2. Set 활용하여 1 ~ 45 까지 번호 가져오기

import java.util.Random

// mutableSetOf를 이용하여 중복검사 로직을 하지 않고 바로 랜덤값을 넣어준다.

fun main() {
    var random = Random()
    var numberSet = mutableSetOf<Int>()
    while(numberSet.size < 6){
        val randomNumber = random.nextInt(45) + 1
        numberSet.add(randomNumber)
    }
    print(numberSet)
}

3. List에 미리 45번까지의 데이터를 가지고 있다가 앞에서 6번째까지 데이터 가져오기

import java.util.Random

/**
 * You can edit, run, and share this code. 
 * play.kotlinlang.org 
 */

fun main() {
    var random = Random()
    var list = mutableListOf<Int>().apply{
        for(i in 1 .. 45){
            this.add(i)
        }
    }
   	list.shuffle()
    print(list.subList(0,6))
}

 

 

 

기본설정인 constraint-layout을 사용

https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout

 

ConstraintLayout  |  Android 개발자  |  Android Developers

 

developer.android.com

 

'안드로이드 > Kotlin' 카테고리의 다른 글

BMI 계산기 - 계산 기능  (0) 2021.06.13
BMI 계산기 - 레이아웃  (0) 2021.06.13
안드로이드 스튜디오 에러  (0) 2021.06.13
Kotlin 개념, 문법  (0) 2021.06.13

코드를 정렬하는 단축키: ctrl + alt + L

 

소스코드 수정

java -> 프로젝트 명 -> MainActivity.kt

 

화면 입력창과 코틀린 소스 변수 연결 시키기

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

//      EditText타입 변수에 각 EditText의 값을 가져온다.
        val heightEditText: EditText = findViewById(R.id.heightEditText)
        val weightEditText = findViewById<EditText>(R.id.weightEditText)

        val resultButton = findViewById<Button>(R.id.resultButton)
    }
}

 

에러 해결 alt + enter

 

버튼 클릭 이벤트 처리

//      버튼 클릭 이벤트 처리
        resultButton.setOnClickListener {
//          로그 찍기
            Log.d("MainActivity","ResultButton 이 클릭되었습니다.")

//          비어있는 값일 경우 경고창을 띄워주고 종료
            if (heightEditText.text.isEmpty() || weightEditText.text.isEmpty()) {
                Toast.makeText(this,"빈 값이 있습니다.", Toast.LENGTH_SHORT).show()
                /*버튼 클릭 함수를 나온다.*/
                return@setOnClickListener
            }

            //          Int형으로 변환하여 변수에 값 저장
            val height:Int = heightEditText.text.toString().toInt()
            val weight:Int = weightEditText.text.toString().toInt()

            Log.d("MainActivity", "height : $height, weight : $weight")

//          MainActivity에서 ResultActivity 호출 Intent(새로운 액티비티 전 화면, 새로 호출할 화면)
            val intent = Intent(this, ResultActivity::class.java)
            startActivity(intent)
        }

 

Intent를 이용하여 다음 화면으로 이동및 데이터 전달 처리를 한다.

참고 사이트

https://developer.android.com/guide/components/intents-filters?hl=ko 

 

인텐트 및 인텐트 필터  |  Android 개발자  |  Android Developers

An Intent is a messaging object you can use to request an action from another app component . Although intents facilitate communication between components in several ways, there are three fundamental use cases: An Activity represents a single screen in…

developer.android.com

 

입력후 결과를 보여줄 Activity를 생성(Result Activity.kt, activity_result.xml)

코틀린 소스파일과 layout화면 을 함께 생성한다.

 

 

아래와 같은 에러가 나온다면 manifests에 등록을 해주어야 한다.

 

Unable to find explicit activity class {com.example.aoppart2chapter01/com.example.aoppart2chapter01.ResultActivity}; have you declared this activity in your AndroidManifest.xml?

계속해서 코드 추가

ResultActivity.kt

package com.example.aoppart2chapter01

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlin.math.pow

class ResultActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

//      Intent로 전송한 데이터를 받는 방법 (intent 이전 화면에서의 Intent 변수명)
        val height = intent.getIntExtra("height",0)
        val weight = intent.getIntExtra("weight",0)

        Log.d("ResultActivity", "height: $height, weight: $weight")

//      pow: 제곱근 함수 사용
        val bmi = weight / (height / 100.0).pow(2.0)
        val resultText = when {
            bmi >= 35.0 -> "고도 비만"
            bmi >= 30.0 -> "중정도 비만"
            bmi >= 25.0 -> "경도 비만"
            bmi >= 23.0 -> "과체중"
            bmi >= 18.0 -> "정상체중"
           else -> "저체중"
        }

//      레이아웃에 정의해둔 요소와 연결시킨다.
        val resultValueTextView = findViewById<TextView>(R.id.bmiResultTextView)
        val resultStringTextView = findViewById<TextView>(R.id.resultTextView)
//      연결된 요소에 데이터 입력
        resultValueTextView.text = bmi.toString()
        resultStringTextView.text = resultText
    }
}

activity_result.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:text="BMI : "
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>

<!--tools:text="33333333":  툴내에서만 확인용으로 보여주는 명령어 앱을 실행시키면 보이지 않는다.-->
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            tools:text="33333333"
            android:id="@+id/bmiResultTextView"
            android:text=""
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
/>

    </LinearLayout>

    <LinearLayout
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:text="결과는 : "
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>
        <TextView
            android:textSize="30sp"
            android:textColor="@color/custom_black"
            android:id="@+id/resultTextView"
            android:text=""
            tools:text="과체중입니다"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"/>

    </LinearLayout>

</LinearLayout>

 

화면

 

 

 

'안드로이드 > Kotlin' 카테고리의 다른 글

로또 추첨기 만들기 - 1  (0) 2021.06.20
BMI 계산기 - 레이아웃  (0) 2021.06.13
안드로이드 스튜디오 에러  (0) 2021.06.13
Kotlin 개념, 문법  (0) 2021.06.13

layout 그리기

res -> layout -> activity_main.xml 파일 수정

androidx.constraintlayout.widget.ConstraintLayout을 LinearLayout으로 수정

LinearLayout: 층층이 나오도록 설정하는것

android:orientation="vertical": 세로로 쌓이도록 설정

match_parent는 부모에 딱 맞춘다. wrap_content는 들어있는 내용크기에 맞춘다.

 

수정 전

수정 후

inputType을 number로 설정하여 숫자만 입력하도록 설정

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">

<!-- match_parent는 부모에 딱 맞춘다. wrap_content는 들어있는 내용크기에 맞춘다.-->
    <TextView
        android:text="신장"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="체중" />

    <EditText
        android:id="@+id/editTextNumber"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="확인하기"/>

</LinearLayout>

 

padding 과 margin으로 여백주기

margin은 요소에 직접 선언하고

padding은 layout 속성에 선언한다.

<LinearLayout 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"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">
  <EditText
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number"/>

 

색상 설정 (res -> values -> colors.xml에서 저장하여 사용 가능하다)

적용

<TextView
        android:textColor="@color/custom_black"
        android:textStyle="bold"
        android:textSize="20sp"
        android:text="신장"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

 

text 값 설정(res -> values -> strings.xml)

적용

<TextView
        android:textColor="@color/custom_black"
        android:textStyle="bold"
        android:textSize="20sp"
        android:layout_marginTop="30dp"
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/weight" />

 

'안드로이드 > Kotlin' 카테고리의 다른 글

로또 추첨기 만들기 - 1  (0) 2021.06.20
BMI 계산기 - 계산 기능  (0) 2021.06.13
안드로이드 스튜디오 에러  (0) 2021.06.13
Kotlin 개념, 문법  (0) 2021.06.13

Gradle project sync faild .... 에러가 발생했을때

https://kadosholy.tistory.com/24

 

안드로이드 스튜디오 - gradle project sync failed. basic functionality (e.g. editing debugging) will not work properly

안드로이드 스튜디오 - gradle project sync failed. basic functionality (e.g. editing debugging) will not work properly 에러 해결방법 안드로이드 스튜디오를 update하거나 잘못 만지면 gradle project sync..

kadosholy.tistory.com

나 같은 경우 help에서 update를 진행한 후 프로젝트를 새로 생성하였다

 

'안드로이드 > Kotlin' 카테고리의 다른 글

로또 추첨기 만들기 - 1  (0) 2021.06.20
BMI 계산기 - 계산 기능  (0) 2021.06.13
BMI 계산기 - 레이아웃  (0) 2021.06.13
Kotlin 개념, 문법  (0) 2021.06.13

자바를 보완하기 위한 언어 (자바와 100% 호환이 된다.)

안드로이드 개발 공식 언어이다.

 

코틀린 공식 사이트

https://kotlinlang.org/

 

Kotlin Programming Language

 

kotlinlang.org

 

함수선언 문법

fun sum(a: Int, b: Int): Int {
	return a + b;
}

fun sum(a: Int, b: Int) = a + b

fun max(a: Int, b: Int) = if (a > b) a else b

변수(var), 상수(val) 선언

val a: Int = 1

val b = 2

val c = 3.14

val d: String
// d = "d의 초기값이 없으면 null이 될 수 있는데, kotlin은 null이 가능한 타입과 아닌 타입이 있기때문에
에러가 발생할 수 있다."
d = "필수로 있어야 하는 구문"

val e: String?

var d: String = "첫번째 초기화"
e = "두 번째 초기화"

For 반복문

for (i in 1..5){
	println(i)
}
// 1 2 3 4 5

for (i in 6 downTo 0 step 2) {
	println(i)
}
// 6 4 2 0

for (i in 1..5 step 3) {
	println(i)
}
// 1 4

val numberList = listOf(100, 200, 300)
for (number in numberList){
	println(number)
}
// 100 200 300

While 반복문

var x = 5
while (x > 0) {
	println(x)
    x--
}
// 5 4 3 2 1

x = 0
while (x > 0) {
 	println(x)
    x--
}
// 출력 없음

var y = 0
do {
	print(y)
    y--
} while (y > 0)
// 0

 

IF 문

var max: Int
if (a > b) {
	max = a
} else {
	max = b
}

// As expression
val max = if (a > b) {
	print("Choose a")
    a
} else {
	print("Choose b")
    b
}

when 문(자바에 switch문 대신)

when (x) {
	1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
    	print("x is neither 1 nor 2")
    }
}

when (x) {
	0, 1 -> print("x == 0 or x == 1")
    else -> print("otherwise")
}

when (x) {
	in 1..10 -> print("x는 1부터 10범위 안에 있음")
    !in 1..20 -> print("x는 1부터 20범위 안에 없음")
    else -> print("otherwiese")
}

when (x) {
	is Int -> print("x는 인트형")
    else -> print("x는 인트형이 아님")
}

 

Null Safe

Integer a = 100;

//null 허용
val b: Int? =100

//null 허용X
val c: Int = 100

a = null;
// 중략
a.sum(); // NullPointException이 날 수도 있음

// null safe 한 코드를 구성해야함
if (a != null) {
	a.sum();
}

b?.sum() // null일 경우 실행하지 않음
c.sum() // 애초에 nullsafe함

 

Scope Function (apply, with, let, also, run)

코드를 좀더 읽기 쉽게 수정할 수 있다

사이트

https://kotlinlang.org/docs/scope-functions.html#function-selection

 

Scope functions | Kotlin

 

kotlinlang.org

Apply함수

객체의 확장함수(자바의 생성자와 같은 역할, 객체를 초기화할 때 사용)

val person = Person().apply{
	firstName = "Fast"
    lastName = "Campus"
}

 

Also 함수

람다 입력값을 받고 다시 리턴(객체의 유효성 확인, 디버깅 용도로 사용)

Random.nextInt(100).also {
	print("getRandomInt() generated value $it")
}

Random.nextInt(100).also { value ->
	print("getRandomInt() generated value $value")
}

 

Let 함수

null이 아닌 객체에서 사용

val number: Int?

// null이 아닐 경우 sum 사용 null일 경우 빈값으로 치환
val sumNumberStr = number?.let {
	"${sum(10, it)}"
}.orEmpty()

 

With 함수

person에 있는 함수를 사용

val person = Person()

with(person) {
	work()
    sleep()
    println(age)
}

 

Run 함수

객체 구성과 결과계산이 한번에 실행될 때 유용

val result = service.run {
	port = 8080
    query()
}

Data Class

데이터를 저장하는 목적으로 만든 클래스

// 생성자, getter, setter 등 모두 만들어 진다.
data class JavaObject(var s: String)

 

Lambda expression

// 자바방식
button.setOnClickListener(new View.OnClickListener() {
	@Override
    public void onClick(View view) {
    	...
    }
})

// kotlin 방식
button.setOnClickListener { v ->
	
}

 

lateinit

변수를 나중에 초기화 하는 방법

var nullableNumber: Int? = null

lateinit var lateinitNumber: Int

// 추후 초기화 하는 코드
lateinintNumber = 10

// 사용할 때
nullableNumber?.add()

lateinitNumber.add()

 

'안드로이드 > Kotlin' 카테고리의 다른 글

로또 추첨기 만들기 - 1  (0) 2021.06.20
BMI 계산기 - 계산 기능  (0) 2021.06.13
BMI 계산기 - 레이아웃  (0) 2021.06.13
안드로이드 스튜디오 에러  (0) 2021.06.13

+ Recent posts