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

自訂 ViewGroup 實作可動態新增的流式標籤

編輯:關於 Android 程式設計

研究自訂 View 的過程中,看到有作者用 ViewGroup 實作浮動標籤,於是照著思路並加入自己的想法,做了一版自己的版本。目前支援動態新增標籤與點擊回應。

一、實作思路

首先是 onMeasure:需要測出 ViewGroup 的寬與高,重點在於當寬度設為 wrap_content 時該怎麼辦。做法是讓每個子 View 先自我測量,再透過 getMeasuredWidth() 與 getMeasuredHeight() 取得尺寸。每加入一個子 View 前,都要判斷「當前行還塞得下嗎」;塞不下就換行,並記錄當前行的最大高度。

再來是 onLayout:核心任務是為每個子 View 定出盒模型的兩個對角點——左上角 (l, t) 與右下角 (r, b),位置就確定了。

二、程式碼

/**
 * 流式標籤:依傳入的資料動態產生標籤
 */
public class DynamicTagFlowLayout extends ViewGroup {

    private List<String> mTags = new ArrayList<String>();

    public DynamicTagFlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int totalHeight = 0;      // ViewGroup 總高度
        int maxLineWidth = 0;     // 所有行中的最大寬度
        int lineMaxHeight = 0;    // 當前行的最大高度
        int currentLineWidth = 0; // 當前行的總寬度
        int childViewWidthSpace = 0;
        int childViewHeightSpace = 0;

        int count = getChildCount();
        MarginLayoutParams layoutParams;

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                // 先讓子 View 測量自己
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
                layoutParams = (MarginLayoutParams) child.getLayoutParams();
                childViewWidthSpace = child.getMeasuredWidth()
                        + layoutParams.leftMargin + layoutParams.rightMargin;
                childViewHeightSpace = child.getMeasuredHeight()
                        + layoutParams.topMargin + layoutParams.bottomMargin;

                if (currentLineWidth + childViewWidthSpace > widthSize) {
                    // 加入這個子 View 會超出寬度上限,需要換行
                    totalHeight += lineMaxHeight;
                    if (maxLineWidth < currentLineWidth) {
                        maxLineWidth = currentLineWidth;
                    }
                    currentLineWidth = childViewWidthSpace;
                    lineMaxHeight = childViewHeightSpace;
                } else {
                    // 當前行還能繼續放
                    currentLineWidth += childViewWidthSpace;
                    if (lineMaxHeight < childViewHeightSpace) {
                        lineMaxHeight = childViewHeightSpace;
                    }
                }
            }
        }

        setMeasuredDimension(
                widthMode == MeasureSpec.EXACTLY ? widthSize : maxLineWidth,
                heightMode == MeasureSpec.EXACTLY ? heightSize : totalHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int currentLine = 1;                       // 目前是第幾行
        List<Integer> lineMaxHeightList = new ArrayList<Integer>(); // 每行最大高度
        int childViewWidthSpace = 0;
        int childViewHeightSpace = 0;
        int lineMaxHeight = 0;
        int currentLineWidth = 0;

        int count = getChildCount();
        MarginLayoutParams layoutParams;

        for (int i = 0; i < count; i++) {
            int cl = 0, ct = 0, cr = 0, cb = 0;
            View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                layoutParams = (MarginLayoutParams) child.getLayoutParams();
                childViewWidthSpace = child.getMeasuredWidth()
                        + layoutParams.leftMargin + layoutParams.rightMargin;
                childViewHeightSpace = child.getMeasuredHeight()
                        + layoutParams.topMargin + layoutParams.bottomMargin;

                if (currentLineWidth + childViewWidthSpace > getWidth()) {
                    // 換行:先把這一行的高度存起來
                    lineMaxHeightList.add(lineMaxHeight);
                    currentLine++;
                    currentLineWidth = childViewWidthSpace;
                    lineMaxHeight = childViewHeightSpace;
                    cl = layoutParams.leftMargin;
                    if (currentLine > 1) {
                        for (int j = 0; j < currentLine - 1; j++) {
                            ct += lineMaxHeightList.get(j);
                        }
                        ct += layoutParams.topMargin;
                    } else {
                        ct = layoutParams.topMargin;
                    }
                } else {
                    // 留在當前行
                    cl = currentLineWidth + layoutParams.leftMargin;
                    if (currentLine > 1) {
                        for (int j = 0; j < currentLine - 1; j++) {
                            ct += lineMaxHeightList.get(j);
                        }
                        ct += layoutParams.topMargin;
                    } else {
                        ct = layoutParams.topMargin;
                    }
                    currentLineWidth += childViewWidthSpace;
                    if (lineMaxHeight < childViewHeightSpace) {
                        lineMaxHeight = childViewHeightSpace;
                    }
                }

                cr = cl + child.getMeasuredWidth();
                cb = ct + child.getMeasuredHeight();
                child.layout(cl, ct, cr, cb);
            }
        }
    }

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

    public void setTags(List<String> tags) {
        if (tags == null) return;
        mTags.clear();
        mTags.addAll(tags);
        for (int i = 0; i < mTags.size(); i++) {
            TextView tv = new TextView(getContext());
            MarginLayoutParams lp = new MarginLayoutParams(
                    MarginLayoutParams.WRAP_CONTENT, MarginLayoutParams.WRAP_CONTENT);
            lp.setMargins(15, 15, 15, 15);
            tv.setLayoutParams(lp);
            tv.setBackgroundResource(R.drawable.tv_bg);
            /*
             * setPadding 一定要放在 setBackgroundResource 之後才有效
             * https://stackoverflow.com/questions/18327498/setting-padding-for-textview-not-working
             */
            tv.setPadding(15, 15, 15, 15);
            tv.setTextColor(Color.WHITE);
            tv.setText(mTags.get(i));
            tv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onClick(v);
                    }
                }
            });
            addView(tv);
        }
        requestLayout();
    }

    private OnTagItemClickListener listener;

    public interface OnTagItemClickListener {
        void onClick(View v);
    }

    public void setOnTagItemClickListener(OnTagItemClickListener l) {
        listener = l;
    }
}

程式碼裡那行註解值得留意:setPadding 必須在 setBackgroundResource 之後呼叫,順序顛倒會失效,這是很容易踩到的小坑。

三、使用方式

public class MainActivity extends Activity {

    private DynamicTagFlowLayout dynamicTagFlowLayout;
    List<String> tags = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_tagflowlayout);

        dynamicTagFlowLayout = (DynamicTagFlowLayout) findViewById(R.id.dynamic_tag);
        dynamicTagFlowLayout.setOnTagItemClickListener(new OnTagItemClickListener() {
            @Override
            public void onClick(View v) {
                TextView tv = (TextView) v;
                Toast.makeText(MainActivity.this, tv.getText().toString(),
                        Toast.LENGTH_SHORT).show();
            }
        });

        initData();
        dynamicTagFlowLayout.setTags(tags);
    }

    private void initData() {
        tags.add("Android 開發");
        tags.add("新聞熱點");
        tags.add("I love you");
        tags.add("Hello World");
        // ...其餘標籤依此類推
    }
}

呼叫 setTags() 之後,元件會依資料筆數動態產生對應數量的 TextView,並自動完成換行排版。

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