[패캠 안드로이드] Part2 Ch2.3 ~ ch2.8 로또번호 추첨기

0
post-thumbnail
post-custom-banner

Part2 Ch2.5 ~ ch2.8 로또번호 추첨기

activity_main.xml

<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">

    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/addButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginEnd="10dp"
        android:backgroundTint="@color/button_color"
        android:text="@string/addButtonText"
        app:layout_constraintEnd_toStartOf="@id/clearButton"
        app:layout_constraintHorizontal_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/numberPicker" />

    <Button
        android:id="@+id/clearButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@color/button_color"
        android:text="@string/clearButtonText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/addButton"
        app:layout_constraintTop_toBottomOf="@id/numberPicker"
        app:layout_constraintTop_toTopOf="@id/addButton" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:gravity="center"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/addButton">

        <TextView
            android:id="@+id/pickedNumberTextView1"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
             />

        <TextView
            android:id="@+id/pickedNumberTextView2"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
             />

        <TextView
            android:id="@+id/pickedNumberTextView3"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
             />

        <TextView
            android:id="@+id/pickedNumberTextView4"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            />

        <TextView
            android:id="@+id/pickedNumberTextView5"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            />
        <TextView
            android:id="@+id/pickedNumberTextView6"
            android:text="1"
            android:textSize="20sp"
            android:textStyle="bold"
            android:background="@drawable/circle_blue"
            android:gravity="center"
            android:visibility="gone"
            tools:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
        />


    </LinearLayout>


    <Button
        android:id="@+id/generateButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:layout_marginBottom="10dp"
        android:backgroundTint="@color/button_color"
        android:text="@string/generateButtonText"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

Circle_yellow.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <solid
        android:color="#FFEB3B"/>
    <size
        android:width="44dp"
        android:height="44dp"/>
</shape>

MainActivity.kt


package fastcampus.aop.part2.chapter02

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.NumberPicker
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible

class MainActivity : AppCompatActivity() {

    private val addButton: Button by lazy{
        findViewById(R.id.addButton)
    }
    private val clearButton: Button by lazy{
        findViewById(R.id.clearButton)
    }
    private val generateButton: Button by lazy{
        findViewById(R.id.generateButton)
    }
    private val numberPicker: NumberPicker by lazy{
        findViewById(R.id.numberPicker)
    }
    private val pickedNumberTextViewList: List<TextView> by lazy{
        listOf<TextView>(
            findViewById<TextView>(R.id.pickedNumberTextView1),
            findViewById<TextView>(R.id.pickedNumberTextView2),
            findViewById<TextView>(R.id.pickedNumberTextView3),
            findViewById<TextView>(R.id.pickedNumberTextView4),
            findViewById<TextView>(R.id.pickedNumberTextView5),
            findViewById<TextView>(R.id.pickedNumberTextView6)
        )
    }

    private var didGenerate = false

    private val pickedNumberSet = hashSetOf<Int>() //mutableSetOf

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

        //numberPicker 속성 초기화
        numberPicker.minValue = 1
        numberPicker.maxValue = 45

        //generateButton 속성 초기화
        initGenerateButton()

        //addButton 속성 초기화
        initAddButton()

        //clearButton 속성 초기화
        initClearButton()
    }

    //generateButton 속성 초기화 함수
   private fun initGenerateButton(){
        generateButton.setOnClickListener{
            val generatedNumberList = (pickedNumberSet.toList() + getRandomNumberList()).sorted()

            generatedNumberList.forEachIndexed { index, number ->
                val textView = pickedNumberTextViewList[index]
                initNumberTextView(textView, number)
            }

                didGenerate = true
        }
   }

    private fun initAddButton(){
        addButton.setOnClickListener {
            //예외 처리 1: 번호 무작위 생성 완료된 경우
            if(didGenerate) {
                Toast.makeText(this, "번호 초기화 후 시도해주세요", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            //예외 처리 2: 이미 번호를 5개 선택한 경우
            if(pickedNumberSet.size >= 5){
                Toast.makeText(this, "번호는 5개까지 선택할 수 있습니다", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            //예외처리 3: 중복된 번호를 선택한 경우
            if(pickedNumberSet.contains(numberPicker.value)){
                Toast.makeText(this, "이미 선택한 번호입니다", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            //번호 선택하기
            pickedNumberSet.add(numberPicker.value)

            val textView = pickedNumberTextViewList[pickedNumberSet.size]
            initNumberTextView(textView, numberPicker.value)
        }
    }
    private fun initClearButton() {
        clearButton.setOnClickListener{
            pickedNumberSet.clear()
            didGenerate = false

            pickedNumberTextViewList.forEach{
                it.isVisible = false
            }
        }
    }
    private fun getRandomNumberList() : List<Int> {
        val randomNumberList = mutableListOf<Int>().apply{
            for(i in 1..45){
                //이미 선택한 번호 제외
                if(pickedNumberSet.contains(i)){
                    continue
                }
                this.add(i)
            }
        }
        randomNumberList.shuffle()
        return randomNumberList.subList(0,6 - pickedNumberSet.size)
    }

    private fun initNumberTextView(textView: TextView, number: Int){
        textView.text = number.toString()
        when (number){
            in 1..10 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_yellow)
            in 11..20 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_blue)
            in 21..30 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_red)
            in 31..40 -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_gray)
            else -> textView.background = ContextCompat.getDrawable(this, R.drawable.circle_green)
        }
        textView.isVisible = true
    }
}

List 정렬 시 주의할 점

  • 아래와 같이 initGenerateButton()함수를 작성한 경우
    -> pickedNumberSet.toList()는 HashSet타입을 List타입으로 변환되며 정렬됨
    -> 그러나 그 외 getRandomNumberList()로 반환받은 리스트는 정렬되지 않음
private fun initGenerateButton(){
        generateButton.setOnClickListener{
            val generatedNumberList = pickedNumberSet.toList() + getRandomNumberList()
			
            generatedNumberList.sorted()

            generatedNumberList.forEachIndexed { index, number ->
                val textView = pickedNumberTextViewList[index]
                initNumberTextView(textView, number)
            }

                didGenerate = true
        }
   }
  • 앱 실행 화면
    -> 왼쪽 : generatedNumberList가 정렬됨
    -> 오른쪽 : pickedNumberSet.toList()의 리스트만 정렬됨

📌참고자료

  • MutableList 타입의 경우: sort, sorted 2가지 정렬 함수 존재
    sort를 사용할 경우 해당 MutableList를 정렬한다
    sorted를 사용할 경우 정렬된 List 타입을 반환하므로 이를 다시 저장해주어야 한다
  • 단, List 타입의 경우: sort 형태는 없고 sorted의 형태만 존재
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글