最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

android - Removing UI Elements in Jetpack Compose - Stack Overflow

programmeradmin4浏览0评论

In earlier Android view system, we used to remove any view from the hierarchy calling the removeView API. This was also removing all the memory related and was supposed to be marked for Garbage Collector for the memory to be free.

Now, that after shifting to Jetpack compose, I'm little confused what is the correct way of removing it from the hierarchy?

Due to it's declarative in nature, if we are invoking any Composable that would be seen on the screen. So, should all the UI elements be conditionally controlled here? Below is one example, how I am doing it currently but it doesn't feel right approach for dynamically removing any composable at run time.

@Composable
fun ExampleScreen (pViewModel : MyViewModel) 
{
    val show : Boolean by pViewModel.show.collectAsState()

    if (show) {
      
         Text (text = "ExampleScreen", fontSize = 16.sp)
    }

}

class MyViewModel : ViewModel () {

  private val private_show : MutableStateFlow<Boolean> = MutableStateFlow<Boolean>(false)
  val show : StateFlow<Boolean> = private_show
}

In earlier Android view system, we used to remove any view from the hierarchy calling the removeView API. This was also removing all the memory related and was supposed to be marked for Garbage Collector for the memory to be free.

Now, that after shifting to Jetpack compose, I'm little confused what is the correct way of removing it from the hierarchy?

Due to it's declarative in nature, if we are invoking any Composable that would be seen on the screen. So, should all the UI elements be conditionally controlled here? Below is one example, how I am doing it currently but it doesn't feel right approach for dynamically removing any composable at run time.

@Composable
fun ExampleScreen (pViewModel : MyViewModel) 
{
    val show : Boolean by pViewModel.show.collectAsState()

    if (show) {
      
         Text (text = "ExampleScreen", fontSize = 16.sp)
    }

}

class MyViewModel : ViewModel () {

  private val private_show : MutableStateFlow<Boolean> = MutableStateFlow<Boolean>(false)
  val show : StateFlow<Boolean> = private_show
}
Share Improve this question asked Mar 17 at 8:36 Rohan PandeRohan Pande 3474 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

What you have written works well without any issues.

But I recommend using collectAsStateWithLifecycle() instead of collectAsState() since the latter is not lifecycle-aware.

For a smoother UI, wrap your composable with AnimatedVisibility instead of using a simple if statement.

AnimatedVisibility(show) {
    Text (text = "ExampleScreen", fontSize = 16.sp)
}
发布评论

评论列表(0)

  1. 暂无评论