Android可以换行的布局

时间:2023-06-05 18:52:50

本文讨论的是下图的这种数据展示方式

Android可以换行的布局

通过本文可以学到的内容

===View绘制的工作流程measure和Layout,即测量和布局;

===动态创建和添加子View,以及设置点击事件的一种思路

1、主要使用的是一个继承自ViewGroup的自定义类NewLineLayout

代码如下:

/**
 * 可以换行的布局
 */

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

import com.orhanobut.logger.Logger;

public class NewLineLayout extends ViewGroup {

    private int mScreenWidth;//屏幕宽度
    private int horizontalSpace, verticalSpace;//子View间距

    public NewLineLayout(Context context) {
        this(context, null);
    }

    public NewLineLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScreenWidth = context.getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //确定此容器的宽高
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //摆放子view
        View child;
        //子view摆放的起始位置
        int left = getPaddingLeft();
        //存储一行view最大的高度,用于子view进行换行时高度的计算
        int maxHeightInLine = 0;
        //存储所有行的高度相加,用于确定此容器的高度
        int allHeight = 0;
        //遍历子view
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            child = getChildAt(i);
            //测量子View宽高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            //两两对比,取得一行中最大的高度
            int childHeight = child.getMeasuredHeight() +
                    child.getPaddingTop() + child.getPaddingBottom();
            if (childHeight > maxHeightInLine) {
                maxHeightInLine = childHeight;
            }
            left += child.getMeasuredWidth() + horizontalSpace +
                    child.getPaddingLeft() + child.getPaddingRight();
            //这一行所有子view相加的宽度大于容器的宽度,需要换行
            if (left > widthSize - getPaddingRight()) {
                //换行的首个子view,起始left为容器的paddingLeft
                left = getPaddingLeft();
                //累积行的总高度
                allHeight += maxHeightInLine + verticalSpace;
                //重置最大高度
                maxHeightInLine = 0;
            } else {
                allHeight += maxHeightInLine;
            }
        }

        if (widthMode != MeasureSpec.EXACTLY) {
            widthSize = mScreenWidth;//如果没有指定宽,则默认为屏幕宽
        }

        if (heightMode != MeasureSpec.EXACTLY) {//如果没有指定高度
            heightSize = allHeight + getPaddingBottom() + getPaddingTop();
        }

        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            //摆放子view
            View child;
            //子view摆放的起始位置
            int left = getPaddingLeft();
            int top = getPaddingTop();
            //存储一行view最大的高度,用于子view进行换行时高度的计算
            int maxHeightInLine = 0;
            for (int i = 0, len = getChildCount(); i < len; i++) {
                child = getChildAt(i);
                //从第二个子view开始算起
                //第一个子view默认从头开始摆放
                if (i > 0) {
                    //两两对比,取得一行中最大的高度
                    if (getChildAt(i - 1).getMeasuredHeight() > maxHeightInLine) {
                        maxHeightInLine = getChildAt(i - 1).getMeasuredHeight();
                    }
                    //当前子view的起始left为 上一个子view的宽度+水平间距
                    left += getChildAt(i - 1).getMeasuredWidth() + horizontalSpace;
                    //这一行所有子view相加的宽度大于容器的宽度,需要换行
                    if (left + child.getMeasuredWidth() > getWidth() - getPaddingRight()) {
                        //换行的首个子view,起始left为容器的paddingLeft
                        left = getPaddingLeft();
                        //top的位置为上一行中拥有最大高度的某个View的高度+垂直间距
                        top += maxHeightInLine + verticalSpace;
                        //将上一行View的最大高度置0
                        maxHeightInLine = 0;
                    }
                }
                //摆放子view
                child.layout(left, top, left + child.getMeasuredWidth(), top + child.getMeasuredHeight());
            }
        }
    }

    /**
     * 设置子view间的水平间距
     *
     * @param horizontalSpace
     */
    public void setHorizontalSpace(int horizontalSpace) {
        this.horizontalSpace = horizontalSpace;
    }

    /**
     * 设置子view间的垂直间距
     *
     * @param verticalSpace
     */
    public void setVerticalSpace(int verticalSpace) {
        this.verticalSpace = verticalSpace;
    }
}

注释比较清楚,耐心点绝对能理解

2、动态创建TextView的方法

/**
* 创建自定义View
*
* @param text 文本内容
*/
private TextView newCustomTextView(String text) {
    TextView textView = new TextView(activity);
    textView.setText(text);
    //指定文字大小
    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, activity.getResources().getDimension(R.dimen.font_text));
    //设置最小宽高
    textView.setMinHeight((int) activity.getResources().getDimension(R.dimen.text_height));
    textView.setMinWidth((int) activity.getResources().getDimension(R.dimen.text_width));
    //设置内边距
    int padding = (int) activity.getResources().getDimension(R.dimen.space_tiny);
    textView.setPadding(padding, 0, padding, 0);
    textView.setGravity(Gravity.CENTER);
    return textView;
}

3、添加子View,利用tag属性关联View点击事件

private String lineString = "_";//自定义分割字符

private void initView() {
    final TextView[] textViewArray = new TextView[dataList.length];
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        String tag = (String) view.getTag();
        if (!StringUtil.isEmpty(tag)) {
            int lineIndex = tag.indexOf(lineString);
            int index = StringUtil.toInt(tag.substring(0, lineIndex), 0);
            //处理按钮组单选的情况
            changeButtonState(textViewArray, index);
            ToastUtil.showShortToast(activity, dataList[index]);
        }
        }
    };
    for (int i = 0; i < dataList.length; i++) {
        textViewArray[i] = newCustomTextView(dataList[i]);
        //组合tag处理单击事件
        String tag = i + lineString + dataList[i];
        textViewArray[i].setTag(tag);
        textViewArray[i].setOnClickListener(onClickListener);
        //添加自定义View
        layContent.addView(textViewArray[i]);
    }
}

4、按钮组的单选实现方法

/**
* 单选按钮组
*
* @param index 根据序号改变按钮组的状态
*/
public void changeButtonState(TextView[] textView, int index) {
    int size = textView.length;
    for (int i = 0; i < size; i++) {
        textView[i].setBackgroundResource(text_normal);
        textView[i].setTextColor(txt_normal);
    }
    textView[index].setBackgroundResource(text_select);
    textView[index].setTextColor(txt_select);
}

===代码地址===