android 不同分辨率 popupwindow大小,Android PopupWindow 疑难杂症之宽度WRAP_CONTENT

一直以来都觉得 Android 中的 PopupWindow 不好用。主要有以下两点:

1、宽度不好控制

2、位置不好控制

AAffA0nNPuCLAAAAAElFTkSuQmCC

今天单说第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 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));

效果:

AAffA0nNPuCLAAAAAElFTkSuQmCC

这样就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值