[TIL]221012 - Kotlin PreCardViewModel 실습

Jimin·2022년 10월 16일
0
post-custom-banner

   private lateinit var binding: ActivityMainBinding
    private val model : CardViewModel by viewModels()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        //View 객체 생성
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        model.cards.observe (this, Observer<IntArray> {
            val res = IntArray(5)

            for (i in it.indices) {
                res[i] = resources.getIdentifier(
                    getCardName(it[i]),
                    "drawable",
                    packageName
                )
            }
            binding.card1.setImageResource(res[0])
            binding.card2.setImageResource(res[1])
            binding.card3.setImageResource(res[2])
            binding.card4.setImageResource(res[3])
            binding.card5.setImageResource(res[4])
        })
        binding.btnDeal.setOnClickListener {
            model.deal()
        }
    }

CardViewModel 클래스

class CardViewModel: ViewModel() {
    private val _cards = MutableLiveData<IntArray>()
    val cards: LiveData<IntArray>
        get() = _cards

    val random = Random(System.currentTimeMillis())

    fun deal() {
        val c = IntArray(5)
        for (i in c.indices) {
            c[i] = random.nextInt(52)
        }
        _cards.value = c
    }
}

  • viewModel이란?
  • MutableLiveData vs LiveData
    • MutableLiveData: get(), set()
    • LiveData: get()

참고 자료
https://velog.io/@ashwon1218/Android-JetPack-ViewModel%EC%9D%B4%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80

post-custom-banner

0개의 댓글