Android使用视图的处理程序来运行代码

3

我看到在AOSP中有很多代码运行类似于:

v.post(new Runnable() {
        @Override
        public void run() {
            // Here comes code
            x += y;
        }
    });

与仅执行简单的 x += y; 相比,这样做有什么优势?

1个回答

0

当视图附加到主用户界面线程时,此运行将获得调用。请查看View类中的post方法。

 /**
     * <p>Causes the Runnable to be added to the message queue.
     * The runnable will be run on the user interface thread.</p>
     *
     * @param action The Runnable that will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     *
     * @see #postDelayed
     * @see #removeCallbacks
     */
    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

如果在 post() 的那一刻视图没有被附加,那么 Runnable 直到被附加后才会运行? - Alex Newman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接