달나라 노트

Android Studio - 주사위 굴리기 본문

Android

Android Studio - 주사위 굴리기

CosmosProject 2021. 3. 23. 00:32
728x90
반응형

 

 

 

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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">


    <TextView
        android:id="@+id/result_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="36sp"
        tools:text="Dice result"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/button_roll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="#676767"
        android:text="Roll"
        android:textColor="#8CB3FF"
        app:layout_constraintTop_toBottomOf="@id/result_text"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

 

 

MainActivity.kt

package com.example.diceroller

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.diceroller.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.buttonRoll.setOnClickListener() {
            dice_roll(6)
        }
    }

    fun dice_roll(dice_sides: Int) {
        var dice_sides = dice_sides
        var dice_result = (1..dice_sides).random()

        binding.resultText.text = dice_result.toString()
    }
}

 

 

 

 

 

 

위 코드는 주사위 굴리기 어플을 만드는 코드입니다.

결과는 아래 이미지와 같습니다.

 

 

 

 

 

 

 

 

 

728x90
반응형
Comments