Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //SCREEN
- @Composable
- fun MainScreen(bGAViewModel: BackgroundAnimationViewModel = viewModel()) {
- val list by bGAViewModel.list.collectAsState()
- Box(Modifier.fillMaxSize()) {
- //adding new item in viewmodel every second
- LaunchedEffect(key1 = true) {
- while (true) {
- delay(1000)
- bGAViewModel.addNewItem()
- }
- }
- //container of items
- Box(modifier = Modifier.fillMaxSize()) {
- list.forEach { item ->
- BackgroundDropItem(
- bGAViewModel = bGAViewModel, backDropItem = item
- )
- }
- }
- //When you tap to button screen will refreshed because of count variable, but viewmodel wont update screen
- Row {
- var count by remember {
- mutableStateOf(0)
- }
- Button(onClick = {
- count++
- Log.d("LOGG", list.toString())
- }) {
- Text(text = "tap")
- }
- Text(text = count.toString())
- }
- }
- }
- //item that's dropping
- @Composable
- fun BackgroundDropItem(
- bGAViewModel: BackgroundAnimationViewModel, backDropItem: BackDropData
- ) {
- Box {
- // animteAs*State animatiob
- val i by animateDpAsState(targetValue = if (backDropItem.state == DropState.Start) 0.dp else 600.dp,
- animationSpec = tween(
- durationMillis = (750..1500).random(), easing = FastOutLinearInEasing
- ),
- label = "",
- finishedListener = {
- bGAViewModel.deleteItem(backDropItem)
- })
- Image(
- painter = painterResource(id = R.drawable.circle),
- contentDescription = "icon",
- modifier = Modifier
- .offset(backDropItem.axisX.dp, i.value.dp)
- .size(50.dp)
- )
- //starting animation
- bGAViewModel.changeState(backDropItem)
- }
- }
- //ViewModel
- class BackgroundAnimationViewModel: ViewModel() {
- private var item: Int = 1
- private var _list = MutableStateFlow(listOf(BackDropData(0)).toMutableList())
- var list: StateFlow<List<BackDropData>> = _list.asStateFlow()
- //adding new BackDropData item in _list
- fun addNewItem() {
- _list.value.add(BackDropData(number = item++, axisX = (0..350).random()))
- }
- //deleting item from _list
- fun deleteItem(item: BackDropData) {
- _list.value.remove(item)
- }
- //change state for animation
- fun changeState(item: BackDropData){
- item.state = DropState.Finish
- }
- }
- //Data
- //State for animation
- enum class DropState {
- Start, Finish
- }
- data class BackDropData(
- val number: Int,
- var state: DropState = DropState.Start,
- //X axis for calculating random X position on screen
- val axisX: Int = 0
- )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement