Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂標籤流式版面配置:單多行切換與單選互動實作

編輯:關於 Android 程式設計

專案裡剛好需要這樣的標籤流式版面配置,做完就在這裡整理出來分享給大家。

效果預覽

要實現的功能

1、單行與多行之間切換顯示;
2、單選與取消選擇。

完整源碼

/**
 * @author jhone
 * @time 2016/08/08
 */
public class LabelView extends ViewGroup {

    private Context context;
    // 目前是否為展開狀態
    private boolean isOpen = false;
    // 用來存放每一行的子 view
    private List<List<View>> mAllChildViews = new ArrayList<>();
    // 用來存放每一行的高度
    private List<Integer> mLineHeight = new ArrayList<>();

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

    public LabelView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LabelView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.context = context;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // 整體最大寬高
        int width = 0;
        int height = 0;
        // 目前這行的寬高
        int lineWidth = 0;
        int lineHeight = 0;

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            if (isOpen) {
                // 疊加後超過行寬就換行
                if (lineWidth + childWidth > sizeWidth) {
                    width = Math.max(width, lineWidth);
                    lineWidth = childWidth;
                    lineHeight = childHeight;
                    height += lineHeight;
                } else {
                    lineWidth += childWidth;
                    lineHeight = Math.max(lineHeight, childHeight);
                }
                // 最後一行沒有被上面的邏輯統計到,這裡用最後一個子 view 補算一次
                if (i == childCount - 1) {
                    width = Math.max(width, lineWidth);
                    height += lineHeight;
                }
            } else {
                // 只顯示第一行
                if (lineWidth + childWidth > sizeWidth) {
                    width = Math.max(width, lineWidth);
                    height = lineHeight;
                    break;
                } else {
                    lineWidth += childWidth;
                    lineHeight = Math.max(lineHeight, childHeight);
                }
            }
        }

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

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

        int width = getWidth();
        int lineWidth = 0;
        int lineHeight = 0;
        List<View> lineViews = new ArrayList<>();

        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();

            // 需要換行
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
                mLineHeight.add(lineHeight);
                mAllChildViews.add(lineViews);
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
                lineViews = new ArrayList<>();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
        // 補上最後一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);

        int left = 0;
        int top = 0;
        int lineCount = mAllChildViews.size();
        for (int i = 0; i < lineCount; i++) {
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
            if (!isOpen) {
                break;  // 只顯示一行
            }
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    // 記錄被點選的位置
    private TextView mask;

    public void addLabels(ArrayList<String> labels) {
        MarginLayoutParams lp = new MarginLayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        int paddingTop = (int) ScreenUtils.dpToPxInt(context, 6);
        int paddingLeft = (int) ScreenUtils.dpToPxInt(context, 10);
        lp.leftMargin = (int) ScreenUtils.dpToPxInt(context, 4);
        lp.rightMargin = (int) ScreenUtils.dpToPxInt(context, 4);
        lp.topMargin = (int) ScreenUtils.dpToPxInt(context, 5);
        lp.bottomMargin = (int) ScreenUtils.dpToPxInt(context, 5);

        for (String label : labels) {
            TextView view = new TextView(context);
            view.setPadding(paddingLeft, paddingTop, paddingLeft, paddingTop);
            view.setText(label);
            view.setTextSize(12);
            view.setTextColor(Color.parseColor("#797671"));
            view.setBackgroundResource(R.drawable.bg_round_black_stroken);
            view.setLayoutParams(lp);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v == mask) {
                        // 再次點擊已選中項 → 取消選中,並回呼 null
                        ((TextView) v).setTextColor(Color.parseColor("#797671"));
                        ((TextView) v).setBackgroundResource(R.drawable.bg_round_black_stroken);
                        mask = null;
                        if (l != null) {
                            l.onLabelChange(null);
                        }
                    } else {
                        // 先把上一個選中項復原,達到單選效果
                        if (mask != null) {
                            mask.setTextColor(Color.parseColor("#797671"));
                            mask.setBackgroundResource(R.drawable.bg_round_black_stroken);
                        }
                        ((TextView) v).setTextColor(Color.parseColor("#06BE6A"));
                        ((TextView) v).setBackgroundResource(R.drawable.bg_round_green_stroken);
                        mask = (TextView) v;
                        if (l != null) {
                            l.onLabelChange((TextView) v);
                        }
                    }
                }
            });
            addView(view, lp);
        }
    }

    private OnLabelChangeListener l;

    public void setOnLabelChangeListener(OnLabelChangeListener l) {
        this.l = l;
    }

    public interface OnLabelChangeListener {
        void onLabelChange(TextView textView);
    }

    /**
     * 單行 / 多行切換
     */
    public void toggle() {
        isOpen = !isOpen;
        requestLayout();
    }
}

整體實現難度不高,註解也寫得比較完整,就不再逐行解釋了。

幾個值得留意的設計點:onMeasure 需要分「展開」與「收起」兩種狀態分別計算,收起時一遇到換行就直接 break,高度只取第一行;onLayout 則先把子 View 按行分組存進 mAllChildViews,再統一定位,這樣後續要擴充成多選或動態增刪標籤都很容易。若想支援多選,只要把單一 mask 換成集合,點擊時累加記錄後回呼即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved