简体   繁体   中英

How can I make a TextView visible for a few seconds and stop other Views from showing?

What I am trying to do is retrieve data from the server when I click a button. When I click the button, I want to show my "Loading..." TextView for 2 seconds, and only then show the data I got from the server. How can I do this?

For now my animation is working, but the data is showing almost instantly. I want to delay that. Using Thread.sleep(2000) causes both the data and Loading to be delayed.

 val loadingAnimation :TextView = findViewById<TextView>(R.id.loadingAnimationTextView)

 val alphaAnim = AlphaAnimation(1.0f, 0.0f)
 alphaAnim.startOffset = 0

 alphaAnim.duration = 2000
 alphaAnim.setAnimationListener(object : AnimationListener {
        override fun onAnimationRepeat(animation: Animation?) {
                 //not sure what code to put here
            }

        override fun onAnimationEnd(animation: Animation) {
               // make invisible when animation completes, you could also remove the view from the layout
               loadingAnimation.setVisibility(View.INVISIBLE)
               }

        override fun onAnimationStart(animation: Animation?) {
               loadingAnimation.setVisibility(View.VISIBLE)
               }
                })
 
 loadingAnimation.setAnimation(alphaAnim)
 Thread.sleep(2000)

You can use the handler for this task.

Handler(Looper.getMainLooper()).postDelayed({
            // Show you data here

 loadingAnimation.setVisibility(View.INVISIBLE)

        }, 2000)

Here, 2000 = 2 seconds

It's probably easier to use the ViewPropertyAnimator stuff:

loadingAnimation.animate()
    .alpha(0)
    .duration(2000)
    .withEndAction {
        // data displaying code goes here
    }.start()

but honestly I don't think there's anything wrong with populating an invisible list, and just making it visible when you want to display it. But that up there is a way to chain runnable code and animations, one after the other

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