为了账号安全,请及时绑定邮箱和手机立即绑定

Android PopupWindow 疑难杂症之宽度WRAP_CONTENT

标签:
Android

一直以来都觉得 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));

效果:
图片描述

这样就可以了。

点击查看更多内容
4人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消