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

前端 未结 2 1319
萌比男神i
萌比男神i 2020-12-12 01:34

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 st

2条回答
  •  臣服心动
    2020-12-12 02:23

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

提交回复
热议问题