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