简体   繁体   English

如何让视图及时消失

[英]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.我正在尝试使用 DataBinding 和 LiveData 来设置 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.如果在 Fragment 的onViewCreated视图设置为不可见,则可以在需要时将其设置为可见,以避免闪烁的视觉效果。

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.这是一个简单的示例,它会是什么样子 - ViewModel 将决定显示什么内容的决定发布给isLoaded LiveData,然后 Fragment 相应地更新视图可见性。

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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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