ListPopupWindow宽度自适应

来源:互联网 发布:使用navicat连接mysql 编辑:程序博客网 时间:2024/05/07 05:29

解决使用ListPopupWindow时发现宽度不适应,显示不全问题
1.先看spinner_item.xml代码,只有一个TextView

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="40dp"    android:gravity="left"    android:textColor="@color/black"    android:textSize="@dimen/sp26" />

2.cars格式为ArrayList<String>,手动添加数据.
3.使用View.inflate获取到spinner_item.xml中的TextView对象,赋值后获取宽度,比较出最大值maxWidth即可
4.调用ListPopupWindow的setWidth(maxWidth)
注意:TextView赋值后,获取宽度前,要调用measure方法,否则获取宽度为0.
代码如下

adapter = new ArrayAdapter(getContext(), R.layout.spinner_item, cars);            popup = new ListPopupWindow(getContext());            int maxWidth = 0;            for (String car : cars) {                TextView textView = (TextView) View.inflate(getContext(), R.layout.spinner_item, null);                textView.setText(car);                textView.measure(0, 0);                maxWidth = maxWidth > textView.getMeasuredWidth() ? maxWidth : textView.getMeasuredWidth();            }            popup.setAdapter(adapter);            popup.setWidth(maxWidth);

qq群492462202欢迎交流。

觉得有用就赞助一下吧!
这里写图片描述

原创粉丝点击