第一次写博客,写得不好之处请大家多多包含,欢迎拍砖。
最近公司项目有个这样的需求,直接上demo截图:
我想到的思路主要有两种:
第一种是在LinearLayout布局中动态添加TextView,设置LinearLayout的属性为水平居中,TextView的属性包裹内容;
第二种是自定义ListView,取item的最大宽度作为ListView的宽度。
感觉第二种的封装性比较好,耦合度比较低,所以就用第二种方法实现了:
自适应宽度的ListView的代码实现:
/**
* Created by xiaoming on 2016/9/6.
* 计算listview 每个item的宽度,取最长长度作为listview的宽度
*/
public class ListViewAdaptWidth extends ListView {
public ListViewAdaptWidth(Context context) {
super(context);
}
public ListViewAdaptWidth(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ListViewAdaptWidth(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getMaxWidthOfChildren() + getPaddingLeft() + getPaddingRight();//计算listview的宽度
super.onMeasure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), heightMeasureSpec);//设置listview的宽高
}
/**
* 计算item的最大宽度
*
* @return
*/
private int getMaxWidthOfChildren() {
int maxWidth = 0;
View view = null;
int count = getAdapter().getCount();
for (int i = 0; i < count; i++) {
view = getAdapter().getView(i, view, this);
view.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
if (view.getMeasuredWidth() > maxWidth)
maxWidth = view.getMeasuredWidth();
}
return maxWidth;
}
}
item的布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textColor="@color/white"
android:text="佛冈" />
</LinearLayout>
主要代码片段:
public void showPopupWindow(View view) {
if (mPopupWindow == null) {
View contentView = LayoutInflater.from(this).inflate(R.layout.popup_listviewadaptwidth, null);
ListViewAdaptWidth listViewAdaptWidth = (ListViewAdaptWidth) contentView.findViewById(R.id.lv_adapt_width);
listViewAdaptWidth.setAdapter(mPopLvAdapter);
listViewAdaptWidth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mPopupWindow != null)
mPopupWindow.dismiss();
}
});
mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
mPopupWindow.setBackgroundDrawable(new ColorDrawable());
mPopupWindow.setOutsideTouchable(true);
}
int[] position = new int[2];
view.getLocationOnScreen(position);
int y = position[1] + view.getMeasuredHeight();
mPopupWindow.showAtLocation(view, Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, y);
}
这是我的第一篇文章,欢迎吐槽、交流。