在項目開發時,經常需要使用popupWindow在EditText下面,做類似于百度搜尋的提示清單的效果,但是popupwindow的寬度的設定,經常需要與EditText保持一緻,如果在onCreate()中直接設定控件的高度、寬度,因為控件還沒有完全加載,并不能擷取到EditText的寬高,而如果使用mesureWidth或者mesureHeight的話,如果EditText本來是在其他父布局中,父布局的寬高也是wrap_content,不确定的,此時即便“預繪制”結束,也可能因為父布局沒有完全繪制結束,導緻擷取到的寬高仍然不是最終的高度,是以此處建議使用這種方式擷取EditText的寬高
//等待界面完全加載結束後,設定suggestPopup的寬度
edt.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
edt.postDelayed(new Runnable() {
@Override
public void run() {
suggestPopup.setWidth(edt.getMeasuredWidth());
}
}, 300);
}
});