Android - 如何判断何时呈现特定视图? [英] Android - How to tell when a specific view has been rendered?

查看:39
本文介绍了Android - 如何判断何时呈现特定视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个常规按钮,我想在上面显示计时器.因此,想象一下按钮的文本作为倒数计时器每秒更改一次.但是,我只需要在按钮完全呈现并准备好在屏幕上显示时才启动此计时器.

I have a regular button that I want to display a timer on. So imagine the text of the button changes every second as a countdown timer. However, I need this timer to only start when the button is fully rendered and ready to go on the screen.

现在我正在片段的 onCreateView() 中启动计时器(它是一个 AsyncTask).这不是那么准确,因为我做了一些我必须拥有的其他加载内容.我可能会在 onCreateView() 底部移动计时器开始,但即使这样也不是很准确.

Right now I'm starting the timer (which is an AsyncTask) in the onCreateView() of a fragment. This isn't that accurate, because I do some other loading stuff that I have to have. I could potentially move the timer start at the bottom of onCreateView() but even that isn't very accurate either.

我看到有一个 OnGlobalLayoutListener 树观察者.但是我想象一下,当即将"绘制整个视图树时?我如何确切知道我的特定按钮何时呈现并对用户可见?

I saw that there's a OnGlobalLayoutListener tree observer. But I imagine this when an entire view tree is "about to be" drawn? how do I know exactly when my particular button is rendered and visible to the user?

推荐答案

OnGlobalLayoutListener() 是正确的去处.可以保证在您的按钮布局后会调用它(完全呈现并准备好在屏幕上显示").例如,在 onCreate() 中你可以这样做:

OnGlobalLayoutListener() is the right place to go. It's guaranteed that it will be called when your button has been layed out ("fully rendered and ready to go on the screen"). For example, in onCreate() you could do:

btn = (Button) findViewById(R.id.bn);   
btn.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        new AsyncTaskTimer.execute();
        // prevent the listener to be called more than once
        btn.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

这篇关于Android - 如何判断何时呈现特定视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆