English 中文(简体)
How is CountDownTimer accessing UI inside OnTick method?
原标题:

How CountDownTimer is accessing UI inside onTick method?

(new CountDownTimer(10000,1000){

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTick(long millisUntilFinished) {
        TextView tv = (TextView)findViewById(R.id.tvLCD);
        tv.setText(Long.toString(millisUntilFinished));
    }           
}).start();
最佳回答

You can get access to UI from thread by Activity.runOnUiTread(), View.post(), View.postDelayed() or via Handler. CountDownTimer uses Handler for this purpose (source).

Read this article for understanding how to use all of these methods.

问题回答

From the links( GreCode - Handler ) in the answer given by @Sergey Glotov, it is clear that countdown timer does not use a seperate thread at all. That is the reason you are able to access the all the UI elements. I don t know why they have used a handler. But it does not spawn a new thread. It runs on the UI thread itself.

CountDownTimer does NOT have any mechanism to access UI inside onTick method. More importantly, from the source code, you can see that internally it uses an handler that is taken at object creation. So it runs on the Thread where the timer was created.

The question is ill-posed, in your case i suppose you can access those views because probably you create the CountDownTimer as anonymous class on an activity. And if you were lucky enough, this was done on the UI thread.





相关问题
Very basic WPF layout question

How do I get this listbox to be maxiumum size, i.e. fill the group box its in. I ve tried width="auto" Height="auto", width="stretch" Height="stretch" annoyingly at the moment, it dynamicly sizes to ...

How to align the text to top of TextView?

How to align the text to top of a TextView? Equivalent Android API for Swings setInsets()? that is top of text should start be in (0,0) of TextView <?xml version="1.0" encoding="utf-8"?> <...

Centring a flow in Shoes

Can I center the contents of a flow in Shoes? I know that a paragraph can be centred like: para Centred paragrpah , :align=> center However, this does not work with flows: flow(:align=> ...

Overlaying with CSS

I want to load a website in an iframe, and overlay the website with some hints about the website that is shown. However, i got stuck at the point that the website has a variable passive white space at ...

How do you normally make a program look beautiful? [closed]

How can I make an Application look nice and not like an amateur pulled it together? I mean graphic-wise. Is there some sort of book you can read regarding beautiful program layouts, etc? I put this ...

热门标签