android - 怎么解釋安卓下這種布局?
問題描述

代碼片段如圖,RelativeLayout定了一個固定的高度。
當(dāng)LinearLayout內(nèi)容較少時,Srollview維持wrapcontent的表現(xiàn)并在RelativeLayout中垂直居中。
當(dāng)LinearLayout內(nèi)容比較多、高度增大到大于RelativeLayout的高度時,ScrollView的高度不會繼續(xù)變大,而是維持跟Relativelayout一樣高并開始可以滾動。
看了一下RelativeLayout和ScrollView的代碼都沒發(fā)現(xiàn)這種“自動加maxHeight”的解釋,求高手指點一下這種表現(xiàn)的原理是什么
問題解答
回答1:控件的高度問題看onMeasure
直接自己繼承ScrollView重寫onMeasure方法, 打印傳進來的參數(shù)如下
@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.d(TAG, 'mode: ' + (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST)); Log.d(TAG, 'size: ' + MeasureSpec.getSize(heightMeasureSpec)); super.onMeasure(widthMeasureSpec, heightMeasureSpec);}
日志打印
mode: truesize: 1581
就可以知道模式是AT_MOST, 也就說高度有限制
看了一下RelativeLayout和ScrollView的代碼都沒發(fā)現(xiàn)這種“自動加maxHeight”的解釋,求高手指點一下這種表現(xiàn)的原理是什么
所以maxHeight是在RelativeLayout 的measureChild中加進去的.
回答2:受 @assistne 啟發(fā),去查了下RelativeLayout的源碼在 getChildMeasureSpec方法中發(fā)現(xiàn)了如下代碼
} else if (childSize == LayoutParams.WRAP_CONTENT) {// Child wants to wrap content. Use AT_MOST// to communicate available space if we know// our max sizeif (maxAvailable >= 0) { // We have a maxmum size in this dimension. childSpecMode = MeasureSpec.AT_MOST; childSpecSize = maxAvailable;} else { // We can grow in this dimension. Child can be as big as it // wants childSpecMode = MeasureSpec.UNSPECIFIED; childSpecSize = 0;} }
而getChildMeasureSpec()方法最終被onMeasure()通過measureChild()和measureChildHorizontal()間接調(diào)用。
排除一些特殊情況,一般情況下,RelativeLayout的子控件,如果設(shè)置為WRAP_CONTENT,則在布局時會有最大尺寸限制。
相關(guān)文章:
1. boot2docker無法啟動2. docker-compose中volumes的問題3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. docker容器呢SSH為什么連不通呢?5. java - SSH框架中寫分頁時service層中不能注入分頁類6. dockerfile - 為什么docker容器啟動不了?7. 關(guān)于docker下的nginx壓力測試8. node.js - antdesign怎么集合react-redux對input控件進行初始化賦值9. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.10. nignx - docker內(nèi)nginx 80端口被占用

網(wǎng)公網(wǎng)安備