Android - How to tell when a specific view has been rendered?

怎甘沉沦 提交于 2019-11-27 08:17:15

问题


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.

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.

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?


回答1:


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



回答2:


You could create a custom button then implement onFinishInflate() or when you initialize the custom button, set it's visibility to invisible and implement onWindowVisibilityChanged(int). Then when you set the button to visible you start the timer. You could also have it be a start button, which when pressed starts the timer and changes what's needed to behave as a timer button.

http://developer.android.com/reference/android/view/View.html



来源:https://stackoverflow.com/questions/22312350/android-how-to-tell-when-a-specific-view-has-been-rendered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!