android - View.post()
阿神
阿神 2017-04-17 15:32:23
0
5
859

View.post()这个方法一般用来做什么?

阿神
阿神

闭关修行中......

reply all(5)
Peter_Zhu

There are two effects that I have the deepest experience with:
1. Everyone knows that calling view.getHeight() in the onCreate() method will return 0, but you can

  view.post(new Runnable() {
            @Override
            public void run() {
                 MainApp.showToastMsg("" + view.getHeight());
            }
        });

to get his height.
2. Use the View.postDelayed() method to prevent multiple unnecessary click events from being triggered by multiple clicks on the view within a period of time:

 view.setEnabled(false);
 view.postDelayed(new Runnable() {
            @Override
            public void run() {
               view.setEnabled(true); 
            }
        },300);
小葫芦

The post contains a Runnable, which means that the work of the Runnable is executed in the UI thread. The UI can be updated directly in the Runnable. However, it should be noted that the Runnable here is not a new thread. Do not perform too complex and time-consuming work to avoid Blocking causes ANR.

刘奇

View has a Handler by default, which belongs to mainLooper. View.post is equivalent to this Handler.post

Ty80

Android APP automatically starts a UIThread, the main thread, after startup. This thread is mainly used to distribute user operation events and interface drawing events. Therefore, in order to maintain a better user experience, time-consuming operations will be executed in other threads. After the execution is completed, the results will be returned to the main thread and displayed. However, the UI cannot be directly manipulated from other threads. This requires a mechanism to transfer information between threads, namely Handler, message queue and Looper.

The Android platform mainly accesses the main thread from other threads in the following ways:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
Handler

For the running process behind View.post, you can refer to the following information:
A kind of implementation and principle of DelayLoad (Part 2)
After reading this analysis, you will understand why View is called in onCreate Only .post can get the height of a View

洪涛

View.post is used to put the Runnable into the queue of the UI thread for execution

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template