简体   繁体   English

TimerTask无法更新UI?

[英]TimerTask can not update UI?

 new Timer().schedule(new TimerTask() {

        public void run() {
            KeyBoardUtil.showKeyBoard(et_search);
        }
    }, 300);

I show the keyboard use TimerTask,and it runs fine. 我显示键盘使用TimerTask,并且运行正常。 how to explain it? 怎么解释呢?

You can use runOnUiThread : 您可以使用runOnUiThread

   runOnUiThread(new Runnable(){
        public void run() {
             // Your code
        }
    });

Or 要么

Handler mainHandler = new Handler(context.getMainLooper());

Runnable myRunnable = new Runnable() {
    @Override 
    public void run() {
        // Your code
    }  
};
mainHandler.post(myRunnable);

developer.android.com developer.android.com

In the previous lesson you learned how to start a task on a thread managed by ThreadPoolExecutor. 在上一课中,您学习了如何在ThreadPoolExecutor管理的线程上启动任务。 This final lesson shows you how to send data from the task to objects running on the user interface (UI) thread. 最后一课向您展示如何将数据从任务发送到在用户界面(UI)线程上运行的对象。 This feature allows your tasks to do background work and then move the results to UI elements such as bitmaps. 此功能允许您的任务执行后台工作,然后将结果移至UI元素(例如位图)。

Every app has its own special thread that runs UI objects such as View objects; 每个应用程序都有自己的特殊线程来运行UI对象,例如View对象; this thread is called the UI thread. 该线程称为UI线程。 Only objects running on the UI thread have access to other objects on that thread. 只有在UI线程上运行的对象才能访问该线程上的其他对象。 Because tasks that you run on a thread from a thread pool aren't running on your UI thread, they don't have access to UI objects. 因为您在线程池中的线程上运行的任务不在您的UI线程上运行,所以它们无权访问UI对象。 To move data from a background thread to the UI thread, use a Handler that's running on the UI thread. 要将数据从后台线程移动到UI线程,请使用在UI线程上运行的Handler。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM