HankeXu
HankeXu

Reputation: 43

Does lazyColumn listen for events when items enter or leave the screen

The item in the list is a video, and I want the video to start automatically when the item is on the screen, stop when it is out the screen and release the resource.

Upvotes: 4

Views: 1418

Answers (1)

Thracian
Thracian

Reputation: 67179

You can achieve this using a DisposableEffect to ready player and its onDispose function to stop and release resource.

Let me add a sample

You can adjust properties here

@Composable
fun MyPlayer(modifier: Modifier, uri: String) {
    val context = LocalContext.current
    val player = SimpleExoPlayer.Builder(context).build()
    val playerView = remember {
        PlayerView(context)
    }

    DisposableEffect(key1 = uri){

        Toast.makeText(context, "player starting", Toast.LENGTH_SHORT).show()
        playerView.useController = false
        playerView.resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FILL
        val mediaItem = MediaItem.fromUri(uri)

        player.setMediaItem(mediaItem)
        playerView.player = player
        player.repeatMode = Player.REPEAT_MODE_ONE
        player.prepare()
        player.playWhenReady = true

        onDispose {
            Toast.makeText(context, "player releasing", Toast.LENGTH_SHORT).show()

            player.stop()
            player.release()
        }
    }

    AndroidView(
        modifier = modifier,
        factory = {
            playerView
        }
    )
}

A filler composable to showcase

@Composable
private fun TextComposable() {
    OutlinedCard {
        Column {
            Image(
                painter = painterResource(id = R.drawable.landscape5),
                contentDescription = null
            )
            Text(
                modifier = Modifier.padding(8.dp),
                text = "Image inside Card",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

List contains elements created for showcase

@Composable
private fun MyVideoList() {
    val myItems = mutableListOf<String>()

    repeat(100) {
        if (it == 6) {
            myItems.add("Video")
        } else {
            myItems.add("Text")
        }
    }

    LazyColumn(
        modifier = Modifier.fillMaxSize(),
        contentPadding = PaddingValues(8.dp),
        verticalArrangement = Arrangement.spacedBy(10.dp)
    ){
        items(items= myItems) {
            if(it== "Text"){
                TextComposable()
            }else{
                MyPlayer(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(4/3f)
                        .border(3.dp, Color.Red),
                    uri = "asset:///floodplain_dirty.mp4"
                )
            }
        }
    }
}

Result

enter image description here

Upvotes: 4

Related Questions