android_View.post(Runnable)在onCreate获取控件宽高分析
来源:互联网 发布:淘宝上的澳洲代购 编辑:程序博客网 时间:2024/05/06 00:19
问题的切入点
在实际开发过程中,我们有时候需要在 activity 中去获取某一个 view 的高度,然后根据该获取的高度去设置其他 view 的高度来达到我们的目的,往往我们都会在 activity#onCreate 直接去 调用 view#getHeight() 但是这个会管用吗,能真正获取到高度吗?这些我们运行下面的实例,然后结合源码的角度去分析这个结果。
代码示例
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final MyView myView = (MyView) findViewById(R.id.myview); int height = myView.getHeight(); int width = myView.getWidth(); Log.e("zeal", "第一次获取myView height:" + height + ";width:" + width); myView.post(new Runnable() { @Override public void run() { int height = myView.getHeight(); int width = myView.getWidth(); Log.e("zeal", "第二次获取myView height:" + height + ";width:" + width); } }); height = myView.getHeight(); width = myView.getWidth(); Log.e("zeal", "第三次获取myView height:" + height + ";width:" + width);}@Overrideprotected void onResume() { super.onResume(); Log.e("zeal", "activity onResume");}
- 布局
<lwj.com.scrollerdemo.MyView android:text="myView" android:layout_width="50dp" android:id="@+id/myview" android:layout_height="50dp"/>
- MyView
public class MyView extends TextView { public MyView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.e("zeal","MyView onMeasure"); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); Log.e("zeal", "MyView onLayout"); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.e("zeal", "MyView onDraw"); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); Log.e("zeal", "MyView onAttachedToWindow"); }}
- MainActivity运行结果:
第一次获取myView height:0;width:0第三次获取myView height:0;width:0activity onResumeMyView onAttachedToWindowMyView onMeasureMyView onMeasureMyView onLayout第二次获取myView height:150;width:150MyView onDrawMyView onMeasureMyView onLayoutMyView onDraw
结合源码分析结果出现的原因
结果是在 post 前后获取 view 宽高的值是为0,只有在 post 中获取到的 view 的宽高才会有值。并且 View 是在 activity onResume 之后将 view attach 到 window 上的。int height = btnScrollBy.getHeight();int width = btnScrollBy.getWidth();之所以有正确的值是因为通过 post 这种方式,view已经测量,布局完毕了,但是若是直接在onCreate获取,view还没有测量,布局完毕,所以获取不到数据。
View.post(Runnable)源码
public boolean post(Runnable action) { final AttachInfo attachInfo = mAttachInfo; if (attachInfo != null) {//在 activity onCreate 中attachInfo 当前还没有赋值 return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true;}
根据 mAttachInfo 是否为空调用不同的代码,那么 mAttachInfo 是在哪里赋值的?纵观 View 源码,发现 mAttachInfo 只有在一处地方赋值,那就是void dispatchAttachedToWindow(AttachInfo info, int visibility),该方法表示当 view 与 window 相关联时回调。onCreate中调用时 mAttachInfo 还没有赋值,所以代码会执行ViewRootImpl.getRunQueue().post(action)
- 通过 ViewRootImpl.getRunQueue().post(action) 将 post 的任务添加 RunnQueue 队列中。
因为 View 还没 attach 到 window 中,也就是当前 mAttachInfo 为 null, 为了让 post 的任务能够执行,系统定义了 RunQueue 类做为队列去管理这些任务,队列中的任务会在 ViewRootImpl#performTraversals() 方法中被执行。也就是在 mAttachInfo 赋值之后通过 Handler 去执行这些任务。
private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();void postDelayed(Runnable action, long delayMillis) { HandlerAction handlerAction = new HandlerAction(); handlerAction.action = action; handlerAction.delay = delayMillis; synchronized (mActions) { mActions.add(handlerAction); }}
通过 post 最终会去调用 postDelayed 中是将 action 封装成一个 HanlderAction 对象添加到 mActions 中去。在 RunQueue 源码中的注释中可以知道,我们将任务添加到任务队列中 RunQueue 之后,会在 ViewRootImpl performTraversals 中执行队列中的任务。贴一下 Google 给的 RunQuee 源码注释:
/** * The run queue is used to enqueue pending work from Views when no Handler is * attached. The work is executed during the next call to performTraversals on * the thread. * @hide */static final class RunQueue { private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>(); void post(Runnable action) { postDelayed(action, 0); } ...}
- 因为 RunQueue 中的任务是在 performTraversals 中执行,所以代码切换到 VeiwRootImpl.performTraversals 方法是怎么去执行 RunQueue 的任务的?
private void performTraversals() { ... getRunQueue().executeActions(mAttachInfo.mHandler); ... performMeasure performLayout performDraw ...}
public ViewRootImpl(Context context, Display display) { mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);}
在该方法中拿到 RunQueue 队列,调用 executeActions 方法去执行队列中的任务。这里的 mAttachInfo 是在 ViewRootImpl 构造中做了赋值操作了。
- 在 RunQueue 中怎么通过 executeActions 去处理任务的?
void executeActions(Handler handler) { synchronized (mActions) { final ArrayList<HandlerAction> actions = mActions; final int count = actions.size(); for (int i = 0; i < count; i++) { final HandlerAction handlerAction = actions.get(i); handler.postDelayed(handlerAction.action, handlerAction.delay); } actions.clear(); }}
遍历队列的所有任务,然后交给 Handler 去执行。到现在代码基本是走通了,但是还是没有解释到为什么在 onCreate 中通过 post 方式就可以拿到 view 的宽高的原因。还记得上面说过的,通过 view.post 的方法将 一个 Runnable 任务添加到 RunQueue 中之后会在 performTraversals中调用执行这个任务,那么 performTraversals 中执行 post 中的任务的代码是 measure 和 layout 前面执行的,那它是怎么保证拿到宽高值的?
final class TraversalRunnable implements Runnable { @Override public void run() { doTraversal(); }}final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void scheduleTraversals() { if (!mTraversalScheduled) { mTraversalScheduled = true; mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier(); mChoreographer.postCallback( Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null); if (!mUnbufferedInputDispatch) { scheduleConsumeBatchedInput(); } notifyRendererOfFramePending(); pokeDrawLockIfNeeded(); }}
在 performTraversals() 中执行 executeActions 是在测量之前调用的,但是却可以在 post 中获取到 view 的宽高值,这是为什么呢?在 scheduleTraversals() 方法中会执行 mChoreographer.postCallback(.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 也就是说将 mTraversalRunnable 作为一个任务添加到主线程的任务队列中,因为 executeActions 内部也是将任务一一的通过 Handler 添加到消息队列中的,因此只有在 mTraversalRunnable 这个任务完毕之后 才会去执行 post 中的任务。因此可以在 post 中获取到 view 的宽高值。
- android_View.post(Runnable)在onCreate获取控件宽高分析
- android 在onCreate中获取控件的宽高
- android 在activity onCreate时获取控件高宽
- Android oncreate中获取控件宽高
- Oncreate里面获取控件宽高。
- 在onCreate()中获取某个View的宽高(post()方法)
- 探究为何:在onCreate中通过View.post能获取宽高
- 在onCreate()中获取某个View的宽高(post()方法)
- 在onCreate()获取View的宽高
- Android在View onCreate时获取控件的宽和高
- Android在onCreate或者在Fragment的onCreateView中获取控件、屏幕的宽高
- 在Activity的onCreate方法中获取控件宽高的N种方法
- Android开发中在onCreate中获取控件的宽高方法
- 在Activity中的OnCreate方法中获取控件的宽高
- 在 onCreate 和 onCreateView 中获取控件宽高的方法
- 在onCreate初中获取View中的宽、高
- android 在onCreate中获取空间宽高
- view在oncreate中获取高和宽
- js事件的分类和介绍
- 栈的应用之一----------进制转换
- android 多线程下载图片--mooc笔记
- Swift3.0 底部弹窗,调用相机和照片
- Enumeration
- android_View.post(Runnable)在onCreate获取控件宽高分析
- Android Crash抓取处理
- ScrollView嵌套ListView冲突问题的最优解决方案
- 无法打开文件atlthunk.lib
- Spring注解@Resource和@Autowired区别
- Android 自带的应用统计服务(UsageStatsService)
- 浅谈grivaty与layout_grivaty的区别
- Acticle 2:javascript函数:声明和调用、有参函数和无参函数、返回值
- 什么情况下会导致内存泄露