简体   繁体   中英

How to make a view disappear in time

I have a fragment that starts after a list item is clicked to display details about the item. Depending on the item I want a view inside the details fragment to either show or not show. I'm trying to use DataBinding and LiveData to set the value of the visibility in the xml. However in the situation where I DON'T want the view to show, the view briefly appears before disappearing and loading the data onto the fragment. How can I make it so that this view is invisible by default or make it disappear before it ever shows.

If you set your view to invisible in the Fragment's onViewCreated you can the set it to visible when needed to avoid the flashing on and off visual effect.

In the case where you do want it to be shown, if starting with it invisible and then showing it after a moment looks bad, you may want to consider starting by hiding all the primary views and showing a loading indicator (like a progress wheel) - then once you have loaded the data and decided which views need to be shown, then you can hide the progress wheel and show the correct views.

Here is a simple example of how that would look - the ViewModel posts the decision of what to show to the isLoaded LiveData and then the Fragment updates the view visibility accordingly.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // ...

    binding.textA.visibility = View.INVISIBLE
    binding.textB.visibility = View.INVISIBLE
    binding.progressBar.visibility = View.VISIBLE

    viewModel.isLoaded.observe(this) { loadedA ->
        binding.progressBar.visibility = View.GONE
        if( loadedA ) {
            binding.textA.visibility = View.VISIBLE
            // show stuff for scenario A
        }
        else {
            binding.textB.visibility = View.VISIBLE
            // show stuff for scenario B
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM