最近有个需求,搜索的历史记录,超过两行需要折叠,后面有个展示展开的按钮,点击按钮展示4行数据。和京东的一样,只是京东会展示全部,但是我们是只会展示4行。本以为会简单,所以在网上找到了对应的代码//www.greatytc.com/p/530e9993f8bc,但是他的这个例子有个问题,就是添加一个新数据,折叠和收缩的按钮丢失了。于是,基于他的代码,砸门修改一下。
先来一个基本的自定义流式布局
public class FlowLayout extends ViewGroup {
/**
* 默认折叠状态
*/
private static final boolean DEFAULT_FOLD = false;
/**
* 折叠的行数
*/
private static final int DEFAULT_FOLD_LINES = 1;
/**
* 左对齐
*/
private static final int DEFAULT_GRAVITY_LEFT = 0;
/**
* 右对齐
*/
private static final int DEFAULT_GRAVITY_RIGHT = 1;
/**
* 是否折叠,默认false不折叠
*/
protected boolean mFold;
/**
* 折叠行数
*/
private int mFoldLines = DEFAULT_FOLD_LINES;
/**
* 对齐 默认左对齐
*/
private int mGravity = DEFAULT_GRAVITY_LEFT;
/**
* 折叠状态
*/
private Boolean mFoldState;
/**
* 是否平均
*/
private boolean mEqually;
/**
* 一行平局数量
*/
private int mEquallyCount;
/**
* 水平距离
*/
private int mHorizontalSpacing;
/**
* 竖直距离
*/
private int mVerticalSpacing;
private static final int MAX_LINE = 3;//从0开始计数
public int maxSize = 9;
private OnFoldChangedListener mOnFoldChangedListener;
public FlowLayout(Context context) {
this(context, null);
}
public FlowLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FlowLayout);
mFold = a.getBoolean(R.styleable.FlowLayout_flow_fold, DEFAULT_FOLD);
mFoldLines = a.getInt(R.styleable.FlowLayout_flow_foldLines, DEFAULT_FOLD_LINES);
mGravity = a.getInt(R.styleable.FlowLayout_flow_gravity, DEFAULT_GRAVITY_LEFT);
mEqually = a.getBoolean(R.styleable.FlowLayout_flow_equally, true);
mEquallyCount = a.getInt(R.styleable.FlowLayout_flow_equally_count, 0);
mHorizontalSpacing = a.getDimensionPixelOffset(R.styleable.FlowLayout_flow_horizontalSpacing, dp2px(8));
mVerticalSpacing = a.getDimensionPixelOffset(R.styleable.FlowLayout_flow_verticalSpacing, dp2px(8));
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//当设置折叠 折叠数设置小于0直接隐藏布局
if (mFold && mFoldLines <= 0) {
setVisibility(GONE);
changeFold(true, true, 0,0, 0);
return;
}
//获取mode 和 size
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int maxIndex = 0;
final int layoutWidth = widthSize - getPaddingLeft() - getPaddingRight();
//判断如果布局宽度抛去左右padding小于0,也不能处理了
if (layoutWidth <= 0) {
return;
}
//这里默认宽高默认值默认把左右,上下padding加上
int width = getPaddingLeft() + getPaddingRight();
int height = getPaddingTop() + getPaddingBottom();
//初始一行的宽度
int lineWidth = 0;
//初始一行的高度
int lineHeight = 0;
//测量子View
measureChildren(widthMeasureSpec, heightMeasureSpec);
int[] wh = null;
int childWidth, childHeight;
int childWidthMeasureSpec = 0, childHeightMeasureSpec = 0;
//行数
int line = 0;
//折叠的状态
boolean newFoldState = false;
//发生折叠的索引
int foldIndex = 0;
//剩余空间
int surplusWidth = widthSize;
int count = getChildCount();
for (int i = 0; i < count; i++) {
final View view = getChildAt(i);
//这里需要先判断子view是否被设置了GONE
if (view.getVisibility() == GONE) {
continue;
}
//如果设置是平局显示
if (mEqually) {
//这里只要计算一次就可以了
if (wh == null) {
//取子view最大的宽高
wh = getMaxWidthHeight();
//求一行能显示多少个
int oneRowItemCount = (layoutWidth + mHorizontalSpacing) / (mHorizontalSpacing + wh[0]);
//当你设置了一行平局显示多少个
if (mEquallyCount > 0) {
//判断当你设定的数量小于计算的数量时,使用设置的,所以说当我们计算的竖直小于设置的值的时候这里并没有强制设置设定的值
//如果需求要求必须按照设定的来,这里就不要做if判断,直接使用设定的值,但是布局显示会出现显示不全或者...的情况。
//if (oneRowItemCount > mEquallyCount) {
/**
* 这里使用固定,设置了一行几个就是集合 显示不全,显示"..."
*/
oneRowItemCount = mEquallyCount;
//}
}
// 根据上面计算的一行显示的数量来计算一个的宽度
int newWidth = (layoutWidth - (oneRowItemCount - 1) * mHorizontalSpacing) / oneRowItemCount;
wh[0] = newWidth;
//重新获取子view的MeasureSpec
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(wh[0], MeasureSpec.EXACTLY);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(wh[1], MeasureSpec.EXACTLY);
}
childWidth = wh[0];
childHeight = wh[1];
//重新测量子view的大小
getChildAt(i).measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
// 自适显示
else {
childWidth = view.getMeasuredWidth();
childHeight = view.getMeasuredHeight();
if(!mFold && line >= 4){
String tag = (String) view.getTag();
if(TextUtils.isEmpty(tag)){
tag = " ";
}
view.setVisibility(GONE);
}
}
//第一行
if (i == 0) {
lineWidth = getPaddingLeft() + getPaddingRight() + childWidth;
lineHeight = childHeight;
} else {
//判断是否需要换行
//换行
if (lineWidth + mHorizontalSpacing + childWidth > widthSize) {
line++;//行数增加
// 取最大的宽度
width = Math.max(lineWidth, width);
//这里判断是否设置折叠及行数是否超过了设定值
if (mFold && line >= mFoldLines) {
line++;
height += lineHeight;
newFoldState = true;
surplusWidth = widthSize - lineWidth - mHorizontalSpacing;
break;
}
//重新开启新行,开始记录
lineWidth = getPaddingLeft() + getPaddingRight() + childWidth;
//叠加当前高度,
height += mVerticalSpacing + lineHeight;
//开启记录下一行的高度
lineHeight = childHeight;
if(!mFold && line > MAX_LINE && maxIndex==0){
//如果不是折叠状态,并且数目大于4行,并且maxIndex没有付过值
maxIndex = i-1;
}
}
//不换行
else {
lineWidth = lineWidth + mHorizontalSpacing + childWidth;
lineHeight = Math.max(lineHeight, childHeight);
if(!mFold && line == MAX_LINE && i >= maxSize && maxIndex==0){
//如果不是折叠状态,并且刚好为4行,并且maxIndex没有付过值,并且条目刚好等于9
maxIndex = i;
}
}
}
// 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较
if (i == count - 1) {
line++;
width = Math.max(width, lineWidth);
height += lineHeight;
}
foldIndex = i;
}
//根据计算的值重新设置
setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width,
heightMode == MeasureSpec.EXACTLY ? heightSize : height);
//折叠状态
changeFold(line > mFoldLines, newFoldState, foldIndex,maxIndex, surplusWidth);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int layoutWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
if (layoutWidth <= 0) {
return;
}
int childWidth, childHeight;
//需要加上top padding
int top = getPaddingTop();
final int[] wh = getMaxWidthHeight();
int lineHeight = 0;
int line = 0;
//左对齐
if (mGravity == DEFAULT_GRAVITY_LEFT) {
//左侧需要先加上左边的padding
int left = getPaddingLeft();
for (int i = 0, count = getChildCount(); i < count; i++) {
final View view = getChildAt(i);
//这里一样判断下显示状态
if (view.getVisibility() == GONE) {
continue;
}
//如果设置的平均 就使用最大的宽度和高度 否则直接自适宽高
if (mEqually) {
childWidth = wh[0];
childHeight = wh[1];
} else {
childWidth = view.getMeasuredWidth();
childHeight = view.getMeasuredHeight();
}
//第一行开始摆放
if (i == 0) {
view.layout(left, top, left + childWidth, top + childHeight);
lineHeight = childHeight;
} else {
//判断是否需要换行
if (left + mHorizontalSpacing + childWidth > layoutWidth + getPaddingLeft()) {
line++;
if (mFold && line >= mFoldLines) {
line++;
break;
}
//重新起行
left = getPaddingLeft();
top = top + mVerticalSpacing + lineHeight;
lineHeight = childHeight;
} else {
left = left + mHorizontalSpacing;
lineHeight = Math.max(lineHeight, childHeight);
}
view.layout(left, top, left + childWidth, top + childHeight);
}
//累加left
left += childWidth;
}
}
//右对齐
else {
int paddingLeft = getPaddingLeft();
// 相当于getMeasuredWidth() - getPaddingRight();
int right = layoutWidth + paddingLeft;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View view = getChildAt(i);
if (view.getVisibility() == GONE) {
continue;
}
//如果设置的平均 就使用最大的宽度和高度 否则直接自适宽高
if (mEqually) {
childWidth = wh[0];
childHeight = wh[1];
} else {
childWidth = view.getMeasuredWidth();
childHeight = view.getMeasuredHeight();
}
if (i == 0) {
view.layout(right - childWidth, top, right, top + childHeight);
lineHeight = childHeight;
} else {
//判断是否需要换行
if (right - childWidth - mHorizontalSpacing < paddingLeft) {
line++;
if (mFold && line >= mFoldLines) {
line++;
break;
}
//重新起行
right = layoutWidth + paddingLeft;
top = top + mVerticalSpacing + lineHeight;
lineHeight = childHeight;
} else {
right = right - mHorizontalSpacing;
lineHeight = Math.max(lineHeight, childHeight);
}
view.layout(right - childWidth, top, right, top + childHeight);
}
right -= childWidth;
}
}
}
/**
* 取最大的子view的宽度和高度
*
* @return
*/
private int[] getMaxWidthHeight() {
int maxWidth = 0;
int maxHeight = 0;
for (int i = 0, count = getChildCount(); i < count; i++) {
final View view = getChildAt(i);
if (view.getVisibility() == GONE) {
continue;
}
maxWidth = Math.max(maxWidth, view.getMeasuredWidth());
maxHeight = Math.max(maxHeight, view.getMeasuredHeight());
}
return new int[]{maxWidth, maxHeight};
}
/**
* 折叠状态改变回调
*
* @param canFold
* @param newFoldState
*/
public void changeFold(boolean canFold, boolean newFoldState, int index,int maxIndex, int surplusWidth) {
if (mFoldState == null || mFoldState != newFoldState) {
if (canFold) {
mFoldState = newFoldState;
}
if (mOnFoldChangedListener != null) {
mOnFoldChangedListener.onFoldChange(canFold, newFoldState, index,maxIndex, surplusWidth);
}
}
}
/**
* 设置是否折叠
*
* @param fold
*/
public void setFold(boolean fold) {
mFold = fold;
if (mFoldLines <= 0) {
setVisibility(fold ? GONE : VISIBLE);
changeFold(true, fold, 0,0, 0);
} else {
requestLayout();
}
}
public void setFoldLines(int mFoldLines) {
this.mFoldLines = mFoldLines;
}
public void setEqually(boolean mEqually) {
this.mEqually = mEqually;
}
/**
* 折叠切换,如果之前是折叠状态就切换为未折叠状态,否则相反
*/
public void toggleFold() {
setFold(!mFold);
}
/**
* dp->px
*
* @param dp
* @return
*/
private int dp2px(int dp) {
return (int) (getContext().getResources().getDisplayMetrics().density * dp);
}
/**
* 设置折叠状态回调
*
* @param listener
*/
public void setOnFoldChangedListener(OnFoldChangedListener listener) {
mOnFoldChangedListener = listener;
}
public interface OnFoldChangedListener {
/**
* 折叠状态时时回调
*
* @param canFold 是否可以折叠,true为可以折叠,false为不可以折叠
* @param fold 当前折叠状态,true为折叠,false为未折叠
* @param index 当前显示的view索引数量
* @param surplusWidth 折叠状态下 剩余空间
*/
void onFoldChange(boolean canFold, boolean fold, int index,int maxIndex, int surplusWidth);
}
}
这里的 MAX_LINE 和 maxSize是我加的,MAX_LINE 记录我最多只能多少行,行数从0开始,所以我这里设置3,maxSize是为了防止一种场景bug,比如:我设置最多4行,然后后台返回的历史记录刚好4行,排满了,但是他不会执行换行代码,所以我就在不换行的时候还判断了一下当前排的子view是不是数据中的最后一个,如果是的,那么也要记录一下index。
接下来就是将它介入适配器
public class FlowListView extends FlowLayout implements FlowAdapter.OnDataChangedListener {
protected FlowAdapter flowAdapter;
public FlowListView(Context context) {
super(context);
}
public FlowListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FlowListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setAdapter(FlowAdapter tagAdapter) {
this.flowAdapter = tagAdapter;
this.flowAdapter.setOnDataChangedListener(this);
updateView();
}
@Override
public void onChanged() {
updateView();
}
private void updateView() {
removeAllViews();
// int count1 = getChildCount();
// for(int x = 0; x < count1;x++){
// Log.d("yanjin","x = "+getChildAt(x).getTag());
// }
if (null == flowAdapter) {
throw new RuntimeException("adapter cannot be empty");
}
int count = flowAdapter.getCount();
for (int i = 0; i < count; i++) {
View tagView = flowAdapter.getView(this, flowAdapter.getItem(i), i);
tagView.setTag(flowAdapter.getItem(i));
flowAdapter.initView(tagView, flowAdapter.getItem(i), i);
addView(tagView);
}
}
}
public abstract class FlowAdapter<T> {
private OnDataChangedListener onDataChangedListener;
private List<T> data;
/**
* 子View创建
*
* @param parent
* @param item
* @param position
* @return
*/
public abstract View getView(ViewGroup parent, T item, int position);
/**
* 初始化View
*
* @param view
* @param item
* @param position
* @return
*/
public abstract void initView(View view, T item, int position);
/**
* 折叠View 默认不设置
*
* @return
*/
public View foldView() {
return null;
}
/**
* 数据的数量
*
* @return
*/
public int getCount() {
return this.data == null ? 0 : this.data.size();
}
/**
* 获取数据
*
* @return
*/
public List<T> getData() {
return data;
}
/**
* 设置新数据
*
* @param data
*/
public void setNewData(List<T> data) {
this.data = data;
notifyDataChanged();
}
/**
* 添加数据
*
* @param data
*/
public void addData(List<T> data) {
if (this.data == null) {
this.data = new ArrayList<>();
}
this.data.addAll(data);
notifyDataChanged();
}
/**
* 添加数据
*
* @param index
* @param data
*/
public void addData(int index, List<T> data) {
if (this.data == null) {
this.data = new ArrayList<>();
}
this.data.addAll(index, data);
notifyDataChanged();
}
/**
* 添加数据
*
* @param data
*/
public void addData(T data) {
if (this.data == null) {
this.data = new ArrayList<>();
}
this.data.add(data);
notifyDataChanged();
}
/**
* 获取指定位置的数据
*
* @param position
* @return
*/
public T getItem(int position) {
if (this.data != null && position >= 0 && position < this.data.size()) {
return this.data.get(position);
}
return null;
}
/**
* 刷新数据
*/
public void notifyDataChanged() {
if (this.onDataChangedListener != null) {
this.onDataChangedListener.onChanged();
}
}
void setOnDataChangedListener(OnDataChangedListener listener) {
this.onDataChangedListener = listener;
}
interface OnDataChangedListener<T> {
void onChanged();
}
}
这个里面的代码都是没改的。照抄
最后再对流式布局封装,加入展开和收缩按钮
public class ExpansionFoldLayout extends FlowListView {
private View upFoldView;
private View downFoldView;
private int mRootWidth = Utils.getScreenWidth();
public ExpansionFoldLayout(Context context) {
this(context, null);
}
public ExpansionFoldLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ExpansionFoldLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
upFoldView = LayoutInflater.from(context).inflate(R.layout.view_item_fold_up, null);
upFoldView.setTag("up");
downFoldView = LayoutInflater.from(context).inflate(R.layout.view_item_fold_down, null);
downFoldView.setTag("down");
upFoldView.setOnClickListener(v -> {
mFold = false;
((ExpansionAndContractionActivity)context).setFlag(false);
flowAdapter.notifyDataChanged();
});
downFoldView.setOnClickListener(v -> {
mFold = true;
((ExpansionAndContractionActivity)context).setFlag(true);
flowAdapter.notifyDataChanged();
});
setOnFoldChangedListener((canFold, fold, index,maxIndex, surplusWidth) -> {
try {
if (canFold) {
Utils.removeFromParent(downFoldView);
addView(downFoldView);
android.util.Log.d("yanjin","maxIndex = "+maxIndex);
for (int x = 0; x < getChildCount(); x++){
View view = getChildAt(x);
if(view.getTag() != null){
Log.d("yanjin","maxIndex tag = "+view.getTag());
}
}
if (fold) {
Utils.removeFromParent(upFoldView);
int upIndex = index(index, surplusWidth);
addView(upFoldView, upIndex);
//标签的后面不能有其他标签,所以好办法就是在他的后面加一个空的标签宽度是屏幕宽度
View emptyView = new View(getContext());
addView(emptyView,upIndex+1,new FrameLayout.LayoutParams(mRootWidth, LayoutParams.MATCH_PARENT));
} else {
if(maxIndex != 0){
Utils.removeFromParent(downFoldView);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
addView(downFoldView,maxIndex,layoutParams);
//标签的后面不能有其他标签,所以好办法就是在他的后面加一个空的标签宽度是屏幕宽度
View emptyView = new View(getContext());
addView(emptyView,maxIndex+1,new FrameLayout.LayoutParams(mRootWidth, LayoutParams.MATCH_PARENT));
}else{
Utils.removeFromParent(downFoldView);
addView(downFoldView);
//标签的后面不能有其他标签,所以好办法就是在他的后面加一个空的标签宽度是屏幕宽度
View emptyView = new View(getContext());
addView(emptyView,new FrameLayout.LayoutParams(mRootWidth, LayoutParams.MATCH_PARENT));
}
}
}
}catch (Exception e){
e.printStackTrace();
}
});
}
private int index(int index, int surplusWidth) {
int upIndex = index;
int upWidth = Utils.getViewWidth(upFoldView);
//当剩余空间大于等于展开View宽度直接加入index+1
if (surplusWidth >= upWidth) {
upIndex = index + 1;
} else { //找到对应的位置
for (int i = index; i >= 0; i--) {
View view = getChildAt(index);
int viewWidth = Utils.getViewWidth(view);
upWidth -= viewWidth;
if (upWidth <= 0) {
upIndex = i;
break;
}
}
}
return upIndex;
}
}
这里要注意的就是setOnFoldChangedListener回调,这里加入展开或者收缩。这里会有一个bug也就是展开或者收缩按钮后面可能会展示一些其他标签按钮,这里为了避免bug,直接在后面加一个充满布局的子view放在展开或收缩按钮后面,这样就不会有这个问题了。
view_item_fold_up.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_fold_view">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="UP"
android:layout_gravity="center"/>
</FrameLayout>
view_item_fold_down.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_fold_view">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Do"
android:layout_gravity="center"/>
</FrameLayout>
//标签的后面不能有其他标签,所以好办法就是在他的后面加一个空的标签宽度是屏幕宽度
View emptyView = new View(getContext());
addView(emptyView,upIndex+1,new FrameLayout.LayoutParams(mRootWidth, LayoutParams.MATCH_PARENT));
适配器
public class SearchHistoryAdapter extends FlowAdapter<String> {
@Override
public View getView(ViewGroup parent, String item, int position) {
return LayoutInflater.from(parent.getContext()).inflate(R.layout.item_search_history, null);
}
@Override
public void initView(View view, String item, int position) {
AppCompatTextView textView = view.findViewById(R.id.item_tv);
textView.setText(item);
textView.setOnClickListener(v -> Toast.makeText(view.getContext(), item, Toast.LENGTH_SHORT).show());
}
}
最后集成在activity中使用
class ExpansionAndContractionActivity : AppCompatActivity() {
public var flag = true
private val list by lazy {
Utils.getHistoryList()
}
private val mAdapter by lazy {
SearchHistoryAdapter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_expansion_and_contraction)
initView()
initData()
}
/**
* 设置值时每次都是重新初始化view
* 解决它加载新数据上拉下拉按钮消失的bug
*/
private fun initData() {
//放入布局中
mRlTest.removeAllViews()
var flowListView: ExpansionFoldLayout =
ExpansionFoldLayout(
this
)
flowListView.setEqually(false)
flowListView.setFoldLines(MIN_LINE)
if(flag){
flowListView.setFold(true)
}else{
flowListView.setFold(false)
}
mAdapter.setNewData(list)
//如果列表返回不为空,那么给流式布局加上列表的最大position
if(list != null && list.size > 0){
flowListView.maxSize = list.size-1
}
flowListView.setAdapter(mAdapter)
mRlTest.addView(flowListView, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT))
}
private fun initView() {
mBtnAdd?.setOnClickListener {
list.add(0,"新增加的"+list.size)
initData()
}
}
companion object{
public var MIN_LINE = 2
}
}
activity_expansion_and_contraction。xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/ff333333"
tools:context=".expansion_and_contraction.ExpansionAndContractionActivity">
<RelativeLayout
android:id="@+id/mRlTest"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/mBtnAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加一个"
android:layout_alignParentBottom="true"/>
</RelativeLayout>