Tugas 4 - Pemrograman Perangkat Bergerak
Hesekiel Nainggolan
5025201054
PPB - I
Aplikasi Roll Dadu
Untuk tugas kali ini, kita bakalan membuat aplikasi roll dadu sederhana menggunakan Empty Activity Project.
Berikut Sumber Kode :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.dadu | |
import android.os.Bundle | |
import androidx.activity.ComponentActivity | |
import androidx.activity.compose.setContent | |
import androidx.compose.foundation.layout.Column | |
import androidx.compose.foundation.layout.fillMaxSize | |
import androidx.compose.foundation.layout.wrapContentSize | |
import androidx.compose.material3.Text | |
import androidx.compose.runtime.Composable | |
import androidx.compose.ui.Modifier | |
import androidx.compose.ui.tooling.preview.Preview | |
import com.example.dadu.ui.theme.DaduTheme | |
import androidx.compose.ui.Alignment | |
import androidx.compose.material3.Button | |
import androidx.compose.ui.res.painterResource | |
import androidx.compose.ui.res.stringResource | |
import androidx.compose.foundation.Image | |
import androidx.compose.foundation.layout.Spacer | |
import androidx.compose.foundation.layout.height | |
import androidx.compose.ui.unit.dp | |
import androidx.compose.runtime.mutableStateOf | |
import androidx.compose.runtime.remember | |
import androidx.compose.runtime.getValue | |
import androidx.compose.runtime.setValue | |
class MainActivity : ComponentActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
DaduTheme { | |
DiceRollerApp() | |
} | |
} | |
} | |
} | |
@Preview(showBackground = true) | |
@Composable | |
fun DiceRollerApp() { | |
DiceWithButtonAndImage(modifier = Modifier | |
.fillMaxSize() | |
.wrapContentSize(Alignment.Center)) | |
} | |
@Composable | |
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) { | |
var result by remember { mutableStateOf(1) } | |
val imageResource = when (result) { | |
1 -> R.drawable.dice_1 | |
2 -> R.drawable.dice_2 | |
3 -> R.drawable.dice_3 | |
4 -> R.drawable.dice_4 | |
5 -> R.drawable.dice_5 | |
else -> R.drawable.dice_6 | |
} | |
Column ( | |
modifier = modifier, | |
horizontalAlignment = Alignment.CenterHorizontally | |
) { | |
Image( | |
painter = painterResource(imageResource), | |
contentDescription = result.toString() | |
) | |
Spacer(modifier = Modifier.height(20.dp)) | |
Button(onClick = { result = (1..6).random() }) { | |
Text(stringResource(R.string.roll)) | |
} | |
} | |
} |
Hasil :
Komentar
Posting Komentar