一直以来都觉得 Android 中的 PopupWindow 不好用。主要有以下两点:
1、宽度不好控制
2、位置不好控制
今天单说第1点。
由于应用有好几种国家的语言,加上各设备宣染效果不完全一样,对popupWindow宽度肯定不能写固定值,一般用系统提供的WRAP_CONTENT,但显示的效果往往不是预期的。
怎样才能正确显示呢,我们可以根据内容来计算宽度(找所有内容中最长的一个),代码如下:
private int measureContentWidth(ListAdapter listAdapter) {
ViewGroup mMeasureParent = null;
int maxWidth = 0;
View itemView = null;
int itemType = 0;
final ListAdapter adapter = listAdapter;
final int widthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int heightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
final int count = adapter.getCount();
for (int i = 0; i < count; i++) {
final int positionType = adapter.getItemViewType(i);
if (positionType != itemType) {
itemType = positionType;
itemView = null;
}
if (mMeasureParent == null) {
mMeasureParent = new FrameLayout(mContext);
}
itemView = adapter.getView(i, itemView, mMeasureParent);
itemView.measure(widthMeasureSpec, heightMeasureSpec);
final int itemWidth = itemView.getMeasuredWidth();
if (itemWidth > maxWidth) {
maxWidth = itemWidth;
}
}
return maxWidth;
}
//调用
ArrayAdapter<String> adapter = new ArrayAdapter<>(mContext, android.R.layout.simple_list_item_1, STRINGS);
popupWindow.setFocusable(true);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setWidth(measureContentWidth(adapter));
效果:
这样就可以了。