博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在启动阶段获取控件大小
阅读量:4207 次
发布时间:2019-05-26

本文共 1614 字,大约阅读时间需要 5 分钟。

10
4

I have a custom view that draws a scrollable bitmap to the screen. In order to initialize it, i need to pass in the size in pixels of the parent layout object. But during the onCreate and onResume functions, the Layout has not been drawn yet, and so layout.getMeasuredHeight() returns 0.

As a workaround, i have added a handler to wait one second and then measure. This works, but its sloppy, and I have no idea how much i can trim the time before I end up before the laout gets drawn.

What I want to know is, how can I detect when a layout gets drawn? Is there an event or callback?

|
   

3 Answers

21
accepted

You can add a tree observer to the layout. This should return the correct width and height. onCreate is called before the layout of the child views are done. So the width and height is not calculated yet. To get the height and width. Put this on the onCreate method

LinearLayout layout = (LinearLayout)findViewById(R.id.YOUD VIEW ID);ViewTreeObserver vto = layout.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override public void onGlobalLayout() {
this.layout.getViewTreeObserver().removeGlobalOnLayoutListener(this); int width = layout.getMeasuredWidth(); int height = layout.getMeasuredHeight(); } });
|
 
This worked. Thanks! ViewTreeObserver is exactly the thing I wanted. –   
 
Thanks a lot! Exactly the example I was looking for, including the immediate removal of the listener upon first trigger. –   

转载地址:http://yllli.baihongyu.com/

你可能感兴趣的文章
【一天一道LeetCode】#58. Length of Last Word
查看>>
【一天一道LeetCode】#59. Spiral Matrix II
查看>>
【一天一道LeetCode】#30. Substring with Concatenation of All Words
查看>>
【一天一道LeetCode】#60. Permutation Sequence.
查看>>
【一天一道LeetCode】#62. Unique Paths
查看>>
【一天一道LeetCode】#61. Rotate List
查看>>
【一天一道LeetCode】#63. Unique Paths II
查看>>
【一天一道LeetCode】#36. Valid Sudoku
查看>>
【一天一道LeetCode】#75. Sort Colors
查看>>
【一天一道LeetCode】#76. Minimum Window Substring
查看>>
【计算机网络 第五版】阅读笔记之一:概述
查看>>
【计算机网络 第五版】阅读笔记之二:物理层
查看>>
【一天一道LeetCode】#83. Remove Duplicates from Sorted List
查看>>
【一天一道LeetCode】#91. Decode Ways
查看>>
【一天一道LeetCode】#92. Reverse Linked List II
查看>>
【一天一道LeetCode】#93. Restore IP Addresses
查看>>
【一天一道LeetCode】#94. Binary Tree Inorder Traversal
查看>>
【一天一道LeetCode】#113. Path Sum II
查看>>
【一天一道LeetCode】#114. Flatten Binary Tree to Linked List
查看>>
【unix网络编程第三版】阅读笔记(二):套接字编程简介
查看>>