利用Android從0到1實現一個流佈局控件

前言

流佈局在在項目中還是會時不時地用到的,比如在搜索歷史記錄,分類,熱門詞語等可用標簽來顯示的,都可以設計成流佈局的展示方式。這裡我從0到1實現瞭一個搜索歷史記錄的流佈局。

演示效果:

實現步驟:

1、創建FlowLayoutView,創建數據源,並添加各個子view。

2、在onMeasure方法中遍歷子view,通過簡單計算剩餘寬度,用集合存儲當前行的幾個子view,再根據子view的累加高度設置自己的最終尺寸。

3、在onLayout方法中,遍歷每一行,遍歷該行的子view,依次調動layout設置子view位置。

核心點:

引入行的概念,每一行存儲自己應該放置的子view。判斷該行剩餘空間和該子view的寬度,來決定能放入該行,還是需要新建下一行來存儲。

主要代碼:

/**
 * description 流佈局viewGroup
 */
public class FlowLayoutView extends ViewGroup {
    private List<Row> rows = new ArrayList<>();
    private int usedWidth;
    /**
     * 當前需要操作的行
     */
    private Row curRow;
    private int verticalPadding = 30;
    private int horizontalPadding = 40;

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        restoreLine();  //每次重新佈局,屬性要初始化,避免onMeasure重復調用混亂問題

        //子view設置寬高為父view大小減去padding值
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //設置每個子view寬高,並且將每個子View歸到自己的行
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);

            //設置子view設置AT_MOST模式,即佈局屬性為wrap_content
            int childWidthSpec = MeasureSpec.makeMeasureSpec(width, widthMode == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : widthMode);
            int childHeightSpec = MeasureSpec.makeMeasureSpec(height, heightMode == MeasureSpec.EXACTLY ? MeasureSpec.AT_MOST : heightMode);
            childView.measure(childWidthSpec, childHeightSpec);

            if (curRow == null) {
                curRow = new Row();
            }

            //根據當前childview寬度和剩餘寬度判斷是否能放進當前行,放不瞭就要換行
            if (childView.getMeasuredWidth() + horizontalPadding > width - usedWidth) {
                //先換行,再放入
                nextLine();
            }

            usedWidth += childView.getMeasuredWidth() + horizontalPadding;
            curRow.addView(childView);
        }

        //將最後一個row加入到rows中
        rows.add(curRow);

        //根據子view組成的高度重設自己高度
        int finalHeight = 0;
        for (Row row : rows) {
            finalHeight += row.height + verticalPadding;
        }

        setMeasuredDimension(width, finalHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int top = 0;
        //遍歷每一行,將每一行子view佈局
        for (Row row : rows) {
            row.layout(top);
            top = top + row.height + verticalPadding;
        }
    }

    /**
     * 換行,需要將當前row存儲,並且創建新的row,新的行使用空間置0
     */
    private void nextLine() {
        rows.add(curRow);
        curRow = new Row();
        usedWidth = 0;
    }

    /**
     * 每次onmeasure需要重置信息
     */
    private void restoreLine() {
        rows.clear();
        curRow = new Row();
        usedWidth = 0;
    }

    /**
     * 用於記錄每一行放置子View的信息
     */
    class Row {
        /**
         * 該行放置的子view
         */
        private List<View> childViews = new ArrayList<>();
        private int height;

        public void addView(View view) {
            childViews.add(view);
            height = view.getMeasuredHeight() > height ? view.getMeasuredHeight() : height;  //高度取最高子view的高度
        }

        public int getSize() {
            return childViews.size();
        }

        /**
         * 將當前childViews進行佈局
         * top 當前hang處於的頂部高度
         */
        public void layout(int top) {
            int leftMargin = 0;
            for (int i = 0; i < childViews.size(); i++) {
                View view = childViews.get(i);
                view.layout(leftMargin, top, leftMargin + view.getMeasuredWidth(), top + view.getMeasuredHeight());
                leftMargin = leftMargin + view.getMeasuredWidth() + horizontalPadding;
            }
        }
    }
}

MainActivity代碼:

public class MainActivity extends AppCompatActivity {
    private FlowLayoutView flowLayoutView;

    private String[] tagTextArray = new String[]{"天貓精靈", "充電臺燈", "睡衣", "手表", "創意水杯", "夏天T恤男", "燈光機械鍵盤",
            "計算機原理", "學霸筆記本", "可口可樂", "跑步機", "旅行箱", "竹漿衛生紙", "吹風機", "洗面奶", "窗簾"};

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

        init();
    }

    private void init() {
        flowLayoutView = findViewById(R.id.flowlayout);

        TextView tvAddTag = findViewById(R.id.tv_addtag);
        tvAddTag.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_tagview, null);
                TextView tvContent = view.findViewById(R.id.tv_content);
                tvContent.setText(tagTextArray[(int) (Math.random()*tagTextArray.length)]);
                flowLayoutView.addView(view);
            }
        });
    }
}

Demo

總結

到此這篇關於利用Android從0到1實現一個流佈局控件的文章就介紹到這瞭,更多相關Android實現流佈局控件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: