티스토리 뷰

728x90
반응형
SMALL

안드로이드 앱 개발의 실전적인 경험을 쌓기 위해, 이번에는 간단한 로또 앱을 만들어보겠습니다. 이 프로젝트를 통해 비동기 작업을 위해 코루틴을 활용하는 방법과 기본적인 안드로이드 앱 개발 방법을 익힐 수 있습니다.

프로젝트 설정

  1. 프로젝트 생성: Android Studio를 열고 "로또 앱"이라는 새로운 안드로이드 프로젝트를 생성합니다.
  2. 레이아웃 작성: activity_main.xml 파일을 열어 로또 번호를 표시할 레이아웃을 작성합니다.
<!-- activity_main.xml -->
<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="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/lottoNumbersTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:text="로또 번호: "
        android:layout_marginBottom="16dp"/>

    <Button
        android:id="@+id/generateLottoButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="로또 번호 생성"
        android:layout_marginTop="16dp"/>
</LinearLayout>

Kotlin 코드 작성

  1. 로또 번호 생성 로직: MainActivity.kt 파일을 열어 로또 번호를 생성하는 비즈니스 로직을 작성합니다.
// MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {

    private lateinit var lottoNumbersTextView: TextView
    private lateinit var generateLottoButton: Button

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

        lottoNumbersTextView = findViewById(R.id.lottoNumbersTextView)
        generateLottoButton = findViewById(R.id.generateLottoButton)

        generateLottoButton.setOnClickListener {
            // 코루틴을 사용하여 비동기 작업 처리
            CoroutineScope(Dispatchers.Main).launch{
                val lottoNumbers = withContext(Dispatchers.Default) {
                    generateLottoNumbers()
                }
                updateLottoNumbers(lottoNumbers)
            }
        }
    }

    private suspend fun generateLottoNumbers(): List<Int> {
        // 로또 번호 생성 로직
        return (1..45).shuffled().take(6).sorted()
    }

    private fun updateLottoNumbers(numbers: List<Int>) {
        val lottoNumbersText = "로또 번호: ${numbers.joinToString(", ")}"
        lottoNumbersTextView.text = lottoNumbersText
    }
}

위 코드에서는 generateLottoNumbers 함수를 통해 1부터 45까지의 숫자를 섞은 뒤, 앞에서부터 6개를 선택하여 정렬한 로또 번호를 생성합니다. 비동기 처리를 위해 코루틴을 사용하였으며, 생성된 로또 번호를 UI에 업데이트하는 작업은 updateLottoNumbers 함수에서 수행합니다.

728x90
반응형
LIST
반응형
250x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함