여러가지 방식의 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

디렉터리 구조

 

manifests

안드로이드 OS에 앱이 어떻게 동작하는지 설정되어있는 파일, 권한에 대한 설정

java

소스코드가 담긴 디렉터리

 

res (코드 외에 나머지 값들이 들어있는 폴더)

drawable: 이미지 리소스가 들어있는 폴더

layout: 앱이 어떻게 그려질지 도화지 같은 폴더

mipmap: 이미지가 들어있는 폴더

values: 앱이 구동할때 설정되어 있는 값들이 저장된 폴더

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

안드로이드 스튜디오 시작  (0) 2021.06.13

사이트

https://developer.android.com/

 

Android 개발자  |  Android Developers

Android 앱 개발자를 위한 공식 사이트입니다. Android SDK 도구 및 API 문서를 제공합니다.

developer.android.com

 

가상머신 설정(android 개발 확인, AVD Manager)

 

디바이스 선택 가능 (Play Strore가 실행되는 Pixel 2로 진행하였다.)

다운 받은후 Finish

실행

 

아래 메뉴를 끌어올려서 Settings 클릭

Settings 에서 아래 메뉴 클릭

 

아래 메뉴 여러번 클릭 -> 개발자 모드

 

상위 메뉴로 이동하여 system 메뉴에 Developer options 메뉴가 생긴 것을 확인

 

프로젝트 생성

Empty Activity 로 생성

 

속성을 지정하고 Finish

프로젝트가 Build 되고 실행 버튼을 누르면 

가상머신에 어플이 실행된다.

 

실제 휴대폰에서 실행하려면 개발자 옵션에서 USB 디버깅을 활성화 설정 해줘야 한다.

 

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

안드로이드 스튜디오 프로젝트 설명  (0) 2021.06.13

+ Recent posts