标签流

  

 有好多应用要给商品或者杂志笔记添加标签,今天有应用涉及到,实现之后整理在这,方便查阅

 

这种流式标签效果,点击标签,改变颜色,并且限制所能添加标签的数量


首先是一个自定义控件,可以直接拿走放在项目中 

package util;

import android.content.Context;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.jianing.practice.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by christy on 16/11/12.
 */

public class FlowLayout extends ViewGroup {

    private static final String TAG = "FlowLayout";

    /**
     * 存储所有的View,按行记录
     */
    private List> mAllViews = new ArrayList>();

    /**
     * 记录每一行的最大高度
     */
    private List mLineHeight = new ArrayList();

    public FlowLayout(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }


    public FlowLayout(Context context) {
        super(context);
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 获得它的父容器为它设置的测量模式和大小
        int sizeWidth = View.MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = View.MeasureSpec.getSize(heightMeasureSpec);
        int modeWidth = View.MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = View.MeasureSpec.getMode(heightMeasureSpec);

        Log.e(TAG, sizeWidth + "," + sizeHeight);

        // 如果是warp_content情况下,记录宽和高
        int width = 0;
        int height = 0;
        /**
         * 记录每一行的宽度,width不断取最大宽度
         */
        int lineWidth = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;

        int cCount = getChildCount();

        // 遍历每个子元素
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            // 得到child的lp
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child
                    .getLayoutParams();
            // 当前子空间实际占据的宽度
            int childWidth = child.getMeasuredWidth() + lp.leftMargin
                    + lp.rightMargin;
            // 当前子空间实际占据的高度
            int childHeight = child.getMeasuredHeight() + lp.topMargin
                    + lp.bottomMargin;
            /**
             * 如果加入当前child,则超出最大宽度,则的到目前最大宽度给width,类加height 然后开启新行
             */
            if (lineWidth + childWidth > sizeWidth) {
                width = Math.max(lineWidth, childWidth);// 取最大的
                lineWidth = childWidth; // 重新开启新行,开始记录
                // 叠加当前高度,
                height += lineHeight;
                // 开启记录下一行的高度
                lineHeight = childHeight;
            } else
            // 否则累加值lineWidth,lineHeight取最大高度
            {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }
            // 如果是最后一个,则将当前记录的最大宽度和当前lineWidth做比较
            if (i == cCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }

        }
        setMeasuredDimension((modeWidth == View.MeasureSpec.EXACTLY) ? sizeWidth
                : width, (modeHeight == View.MeasureSpec.EXACTLY) ? sizeHeight
                : height);

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        mAllViews.clear();
        mLineHeight.clear();

        int width = getWidth();

        int lineWidth = 0;
        int lineHeight = 0;
        // 存储每一行所有的childView
        List lineViews = new ArrayList();
        int cCount = getChildCount();
        // 遍历所有的孩子
        for (int i = 0; i < cCount; i++)
        {
            View child = getChildAt(i);
            ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child
                    .getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 如果已经需要换行
            if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth > width)
            {
                // 记录这一行所有的View以及最大高度
                mLineHeight.add(lineHeight);
                // 将当前行的childView保存,然后开启新的ArrayList保存下一行的childView
                mAllViews.add(lineViews);
                lineWidth = 0;// 重置行宽
                lineViews = new ArrayList();
            }
            /**
             * 如果不需要换行,则累加
             */
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin
                    + lp.bottomMargin);
            lineViews.add(child);
        }
        // 记录最后一行
        mLineHeight.add(lineHeight);
        mAllViews.add(lineViews);

        int left = 0;
        int top = 0;
        // 得到总行数
        int lineNums = mAllViews.size();
        for (int i = 0; i < lineNums; i++)
        {
            // 每一行的所有的views
            lineViews = mAllViews.get(i);
            // 当前行的最大高度
            lineHeight = mLineHeight.get(i);

            Log.e(TAG, "第" + i + "行 :" + lineViews.size() + " , " + lineViews);
            Log.e(TAG, "第" + i + "行, :" + lineHeight);

            // 遍历当前行所有的View
            for (int j = 0; j < lineViews.size(); j++)
            {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE)
                {
                    continue;
                }
                ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) child
                        .getLayoutParams();

                //计算childView的left,top,right,bottom
                int lc = left + lp.leftMargin;
                int tc = top + lp.topMargin;
                int rc =lc + child.getMeasuredWidth();
                int bc = tc + child.getMeasuredHeight();

                Log.e(TAG, child + " , l = " + lc + " , t = " + t + " , r ="
                        + rc + " , b = " + bc);

                child.layout(lc, tc, rc, bc);

                left += child.getMeasuredWidth() + lp.rightMargin
                        + lp.leftMargin;
            }
            left = 0;
            top += lineHeight;
        }

    }

    /**
     * 返回当前ViewGroup相关联的LayoutParams
     */
    @Override
    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new ViewGroup.MarginLayoutParams(getContext(), attrs);
    }

    public TextView addView(String tags) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0,40,15);//左上右下
        TextView textView = new TextView(this.getContext());
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(getResources().getColor(R.color.black));
        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//加粗
        textView.setSelected(false);
        textView.setTextSize(14);
        textView.setPadding(20,20,20,20);
        textView.setSingleLine();
        textView.setEllipsize(TextUtils.TruncateAt.valueOf("END"));
        textView.setText(tags);
        this.addView(textView, params);
        return textView;
    }

}

然后在项目布局中引用这个自定义控件


xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test_biaoqian"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.jianing.practice.TestBiaoqian">

            android:id="@+id/floLayout"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content">


 接下来就是在Activity里面实现逻辑功能

package com.jianing.practice;

import android.app.Activity;
import android.graphics.Color;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import util.BussinessUtil;
import util.FlowLayout;
import util.RoundGroupView;

import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class TestBiaoqian extends Activity {
    private FlowLayout floLayout;
    private String[] tags = {"日系", "韩系", "肉肉女", "品牌", "美妆", "冬天", "牛仔", "中学生", "大学生"};
    private List tagList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_biaoqian);
        floLayout = (FlowLayout) findViewById(R.id.floLayout);
        for (int i = 1; i < tags.length; i++){
            final String tag = tags[i];
            final TextView textView = floLayout.addView(tag);
            textView.setBackgroundResource(R.drawable.biaoqian_selected_drawable);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (textView.isSelected()) {
                        removeTag(tag);
                        textView.setSelected(false);
                        String tagText = textView.getText().toString();
                    } else {
                        tagList.add(tag);
                        if (tagList.size() > 3){
                            Toast.makeText(TestBiaoqian.this,"最多只能选择3个",Toast.LENGTH_SHORT).show();
                            return;
                        }
                        textView.setSelected(true);

                    }
                }
            });
        }
    }

    private void removeTag(String curTag){
        for (int  i = 1 ; i<tagList.size(); i ++){
            String taga = tagList.get(i);
            if (BussinessUtil.isValid(curTag) && curTag.equals(taga)){
                tagList.remove(i);
                break;
            }
        }
    }
}

到现在为止已经可以实现标签流了,若要规定一行显示几个标签,则要在自定义空间里面根据屏幕的宽度设置显示的标签数量

比如规定一行显示三个标签

则应该设置   标签的宽度 = (屏幕总宽度  -  标签总控件两边的padding值  -  三个标签之间的两个padding值)   /   3

在自定义控件这个位置设置即可


你可能感兴趣的:(Android)