搬磚的時(shí)候,需要在popupwindow里嵌套一個(gè)ListView用來展示動(dòng)態(tài)菜單。重寫了ListView的高度為所有的Item高度之和。
item:
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="10dp"
style="@null"
android:maxHeight="45dp"
android:background="@drawable/box"
android:text="取消"
android:textColor="#1a99f3"
android:textSize="15sp" />
這里可以看到,我聲明了高度為45dp。但是添加到ListView的時(shí)候,卻發(fā)現(xiàn)在手機(jī)上顯示的高度明顯大于45dp。

image
根據(jù)圖片我們可以看到,下面三個(gè)按鈕顯示的高度跟第一個(gè)顯示的高度,差了差不多兩倍多的高度。
原來原因在這里:
我們?cè)谑鞘褂?/p>
inflater.inflate(R.layout.item_popumenu, root, attachToRoot);
來添加到父布局中,但是對(duì)于這幾個(gè)參數(shù)卻沒有去研究。以下是我在網(wǎng)上找到的:
1. 如果root為null,attachToRoot將失去作用,設(shè)置任何值都沒有意義。
2. 如果root不為null,attachToRoot設(shè)為true,則會(huì)給加載的布局文件的指定一個(gè)父布局,即root。
3. 如果root不為null,attachToRoot設(shè)為false,則會(huì)將布局文件最外層的所有l(wèi)ayout屬性進(jìn)行設(shè)置,當(dāng)該view被添加到父view當(dāng)中時(shí),這些layout屬性會(huì)自動(dòng)生效。
4. 在不設(shè)置attachToRoot參數(shù)的情況下,如果root不為null,attachToRoot參數(shù)默認(rèn)為true。
其實(shí)也看得我云里霧里,但是大概知道解決的方法了。
View view = inflater.inflate(R.layout.item_popumenu, parent, false);
這里的parent一定要填它的父布局,第三個(gè)參數(shù)設(shè)置為false就好了。