美文网首页
自定义标签布局(流布局)

自定义标签布局(流布局)

作者: 古龙小蓝瓶 | 来源:发表于2017-07-28 10:58 被阅读0次

    相信大家在做应用的时候经常会遇到显示标签的情况,例如(“上班族,天枰座”这样的),若干个标签长短不一,每个标签之间还有一定的间隙,并且一行显示不下之后,下一个标签显示就需要换行,本篇文章就自定义一个View,来实现所说的这个效果。

    首先我们先来看看实现以后是什么样的:

    Paste_Image.png

    通过这个实际的实现效果我们可以做出下面的分析:
    1.每个item的宽度不同
    2.行/列之间有间隔
    3.数据和布局进行分离,并且布局可以自定义,于是我们考虑利用android的adapter的特性进行实现
    4.有自动换行的功能

    这个View大概要实现上面的效果,下面就开始撸码:
    先建立好这个View,继承自ViewGroup:

    public class TagView extends ViewGroup {
    }
    

    为了让其使用更加灵活,我们自定义几个属性:

    <declare-styleable name="TagView">
            <attr name="maxLine" format="integer" />//最多允许多少行,超过的就不进行显示了
            <attr name="itemSpace" format="dimension" />//每个item之间的宽度(每行的高度,也可以多定义一个高度)
            <attr name="gravity" format="enum">////子View摆放时贴着父布局上边还是下边
                <enum name="top" value="1" />
                <enum name="bottom" value="2" />
            </attr>
        </declare-styleable>
    

    定义好了以后,我们就可以在XML文件里画布局了:

      <com.test.xiao.TagView
                android:id="@+id/gv_tag"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@id/iv_photo"
                android:layout_alignParentLeft="true"
                android:layout_below="@id/tv_content"
                android:layout_toLeftOf="@id/iv_photo"
                app:gravity="bottom"//贴着下边进行摆放
                app:itemSpace="3dp"
                app:maxLine="2" />
    

    item的布局如下:

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/tv_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/shape_main_tag_sub"//橙色的背景
        android:ellipsize="end"
        android:gravity="center"
        android:maxLines="1"
        android:paddingBottom="1dp"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:paddingTop="1dp"
        android:text="TextView01"
        android:textColor="@color/white"
        android:textSize="@dimen/ss_small_textSize" />
    

    好了,这些准备工作完成以后,我们就可以开始实现View的功能了,首先定义好相关变量并进行初始化:

    public class TagView extends ViewGroup {
    private int itemSpace = 0;//item之间的间距
        private Adapter mAdapter;//获取数据和子item的适配器,这个adapter就是android原生提供的adapter
        private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(项目中暂时未用到垂直需求,所以暂时不需要)
        private SparseArray<SparseArray<View>> views;//用于记录第几行,第几个item
        private SparseArray<Integer> maxHeights;//记录每行的最大高度
        private int maxLine;//设置最大的行数
        private int gravity;//子View贴着上边还是下边(默认上边),1是上边,2是下边
    public TagView(Context context) {
            super(context);
            init(null);
        }
    
        public TagView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(attrs);
        }
    
        public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(attrs);
        }
    
        private void init(AttributeSet attributeSet) {
            views = new SparseArray<>();
            maxHeights = new SparseArray();
            if (attributeSet == null) {
                itemSpace = Utils.dp2px(getContext(), 5);
                maxLine = 10;// 默认最大行数
            } else {
                TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
                itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
                gravity = array.getInt(R.styleable.TagView_gravity, 1);
                maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
                array.recycle();
            }
        }
    }
    

    接下来我们需要在onMeasure里通过adapter获取到相关的view,并且测量出每个view的宽度和高度,根据宽度来计算出我们需要多少行,每行分别需要列来放这些item:

     @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int needWidth = MeasureSpec.getSize(widthMeasureSpec);
            int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
            int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
            int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
            if (mAdapter != null && mAdapter.getCount() > 0) {//如果adapter没有数据,则不进行绘制,直接调用super.onMeasure
                View child = null;//从adaper中获取的子View
                int childWidth = 0;//子View的宽度
                int currentLineWidth = 0;//当前行的总宽度
                int currentLine = 0;//当前是第几行
                int currentElement = 0;//当前行的第几个元素
                int maxHeight = 0;//当前行的最大高度
                int resultHeihgt = 0;//通过子View的测量情况最终算出来的父View高度
                boolean isMaxLine = false;//当前是否已经到达最大行
                for (int i = 0; i < mAdapter.getCount(); i++) {//通过adapter来遍历测量所有的子View
                    if (currentLine == maxLine) {//到达最大行数时,如果还有下一行,我们就不进行显示了
                        isMaxLine = true;
                        break;
                    }
                    child = mAdapter.getView(i, null, this);
                    measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//获取子控件大小
                    childWidth = child.getMeasuredWidth();
                    if (currentLineWidth == 0) {//已经到达新的一行
                        views.put(currentLine, new SparseArray<>());//新建一个用来存放新的一行元素的集合
                    }
                    if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要换行
                        resultHeihgt += maxHeight + itemSpace;
                        maxHeights.put(currentLine, maxHeight);
                        currentLine++;
                        currentLineWidth = 0;
                        currentElement = 0;
                        i--;
                    } else {
                        if (child.getMeasuredHeight() > maxHeight) {
                            maxHeight = child.getMeasuredHeight();//计算本行的最大高度,在layout时,每行的高度就以最大高度为准
                        }
                        views.get(currentLine).put(currentElement, child);//在测量完了,并且分析好这个元素的位置后,将其放入集合中,待之后onLayout时进行摆放
                        currentElement++;
                        currentLineWidth += itemSpace + childWidth;
                    }
                }
                if (resultHeihgt == 0) {//当前item仅有一行
                    resultHeihgt = maxHeight;
                    maxHeights.put(0, maxHeight);
                } else {//当前item不止一行,且未到达最大行数限制,到这里时,需要补齐最后一行的高度数据
                    if (!isMaxLine) {
                        resultHeihgt += maxHeight;//
                        maxHeights.put(currentLine, maxHeight);
                    }
                }
                setMeasuredDimension(needWidth, resultHeihgt);//设置最终的宽高
            } else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
    
        }
    

    通过onMeasure,我们通过每个item的宽高计算出了TagView的宽高,要显示的行数,每行的高度以及每行的元素及其所处的位置(存放到了views中),通过这些得到的内容,接下来我们就要在onLayout中计算出每个item应该摆放的具体位置了:

    //在这个方法里我们要确定每个View摆放的位置
    @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            if (mAdapter != null && mAdapter.getCount() > 0) {
                View view;//当前要进行摆放的子View
                View lastView;//当前摆放的子View左边的View
                int childLeft, childRight, childTop, childBottom;
                for (int i = 0; i < views.size() && i < maxLine; i++) {//这个循环用来循环行数
                    for (int j = 0; j < views.get(i).size(); j++) {//这个循环用来循环每行的列数
                        view = views.get(i).get(j);//第i行第j个元素
                        childLeft = 0;
                        for (int k = 0; k < j; k++) {//通过前面所有View的宽度相加,得到当前子View的left位置
                            lastView = views.get(i).get(k);
                            childLeft += lastView.getMeasuredWidth() + itemSpace;
                        }
                        childRight = childLeft + view.getMeasuredWidth();
    //确定子View上下的位置,根据gravity的不同(1是靠近父View顶部摆放,2是靠近父View底部摆放)
                        if (gravity == 1) {
                            childTop = 0;
                            for (int k = 0; k < i; k++) {//通过前面所有高度行数相加,得到最终的上边位置
                                childTop += maxHeights.get(k) + itemSpace;
                            }
                        } else {
                            childTop = b - t;//b-t为最后一行的底部
                            for (int k = views.size() - 1 - i; k >= 0; k--) {//第一行的top位置是从最底部算起,后面所有行的高度+自身的高度值+行与行之间的空隙
                                childTop -= (maxHeights.get(k) + itemSpace);
                            }
                            childTop += itemSpace;//这里要加上多减去的空间
                        }
    
                        childBottom = childTop + view.getMeasuredHeight();
                        view.layout(childLeft, childTop, childRight, childBottom);
                        addView(view);
                    }
                }
            }
        }
    

    对于adapter,我们要给出一个可以进行设置的方法:

    public void setAdapter(Adapter adapter) {
            mAdapter = adapter;
            invalidate();
        }
    

    使用的时候,我们这样使用(采用的是效果图中的数据):

    String[] testTags = new String[]{"ssssss", "大家得人生", "ssdsjdj", "我们和小李都有", "放下一切", "大大大大大大多多"};
    public void onCreate(Bundle saveInstanceStates){
    ...
    TagView gv_tag = findViewById(R.layout.gv_tag);
    gv_tag.setAdapter(new ArrayAdapter<>(context, R.layout.item_main_grid_sub_tag, R.id.tv_item, data.getTags()));//采用adapter方式比较灵活
    ...
    }
    
    

    完整代码如下:

    /**
     * Created by LiXiaoSong on 2017/7/10.
     * 自定义Tagview,用于显示流布局
     */
    
    public class TagView extends ViewGroup {
        private int itemSpace = 0;//item之间的间距
        private Adapter mAdapter;//这里传入的adapter仅仅使用了其简单的功能
        private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(项目中暂时未用到垂直需求,所以暂时不需要)
        private SparseArray<SparseArray<View>> views;//用于记录第几行,第几个item
        private SparseArray<Integer> maxHeights;//记录每行的最大高度
        private int maxLine;//设置最大的行数
        private int gravity;//子View贴着上边还是下边(默认上边),1是上边,2是下边
    
        public TagView(Context context) {
            super(context);
            init(null);
        }
    
        public TagView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(attrs);
        }
    
        public TagView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init(attrs);
        }
    
        private void init(AttributeSet attributeSet) {
            views = new SparseArray<>();
            maxHeights = new SparseArray();
            if (attributeSet == null) {
                itemSpace = Utils.dp2px(getContext(), 5);
                maxLine = 10;// 默认最大行数
            } else {
                TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
                itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
                gravity = array.getInt(R.styleable.TagView_gravity, 1);
                maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
                array.recycle();
            }
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int needWidth = MeasureSpec.getSize(widthMeasureSpec);
            int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
            int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
            int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
            if (mAdapter != null && mAdapter.getCount() > 0) {
                View child = null;
                int childWidth = 0;
                int currentLineWidth = 0;
                int currentLine = 0;//当前行数
                int currentElement = 0;
                int maxHeight = 0;//当前行数最大高度
                int resultHeihgt = 0;
                boolean isMaxLine = false;
                for (int i = 0; i < mAdapter.getCount(); i++) {//这里用来存放子View的元素
                    if (currentLine == maxLine) {
                        isMaxLine = true;
                        break;
                    }
                    child = mAdapter.getView(i, null, this);
                    measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//获取子控件大小
                    childWidth = child.getMeasuredWidth();
                    if (currentLineWidth == 0) {//新的一行
                        views.put(currentLine, new SparseArray<>());
                    }
                    if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要换行
                        resultHeihgt += maxHeight + itemSpace;
                        maxHeights.put(currentLine, maxHeight);
                        currentLine++;
                        currentLineWidth = 0;
                        currentElement = 0;
                        i--;
                    } else {
                        if (child.getMeasuredHeight() > maxHeight) {
                            maxHeight = child.getMeasuredHeight();
                        }
                        views.get(currentLine).put(currentElement, child);
                        currentElement++;
                        currentLineWidth += itemSpace + childWidth;
                    }
                }
                if (resultHeihgt == 0) {//当前item仅有一行
                    resultHeihgt = maxHeight;
                    maxHeights.put(0, maxHeight);
                } else {//如果不是,补齐最后一行的数据
                    if (!isMaxLine) {
                        resultHeihgt += maxHeight;//
                        maxHeights.put(currentLine, maxHeight);
                    }
                }
                setMeasuredDimension(needWidth, resultHeihgt);
            } else {
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
    
        }
    
        @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            if (mAdapter != null && mAdapter.getCount() > 0) {
                View view;
                View lastView;//它前面的View
                int childLeft, childRight, childTop, childBottom;
                for (int i = 0; i < views.size() && i < maxLine; i++) {
                    for (int j = 0; j < views.get(i).size(); j++) {
                        view = views.get(i).get(j);//第i行第j个元素
                        childLeft = 0;
                        for (int k = 0; k < j; k++) {//通过前面所有View的宽度相加,得到最终的左边位置
                            lastView = views.get(i).get(k);
                            childLeft += lastView.getMeasuredWidth() + itemSpace;
                        }
                        childRight = childLeft + view.getMeasuredWidth();
                        childTop = 0;
                        if (gravity == 1) {
                            for (int k = 0; k < i; k++) {//通过前面所有高度行数相加,得到最终的上边位置
                                childTop += maxHeights.get(k) + itemSpace;
                            }
                        } else {
                            childTop = b - t;//设置一个底部
                            for (int k = views.size() - 1 - i; k >= 0; k--) {//通过前面所有高度行数相加,得到最终的上边位置
                                childTop -= (maxHeights.get(k) + itemSpace);
                            }
                            childTop += itemSpace;
                        }
    
                        childBottom = childTop + view.getMeasuredHeight();
                        view.layout(childLeft, childTop, childRight, childBottom);
                        addView(view);
                    }
                }
            }
        }
    
        public void setAdapter(Adapter adapter) {
            mAdapter = adapter;
            invalidate();
        }
    }
    

    本文到此结束,如果有什么问题,欢迎一起讨论。

    相关文章

      网友评论

          本文标题:自定义标签布局(流布局)

          本文链接:https://www.haomeiwen.com/subject/gfttlxtx.html