adapter模式實現流式佈局(自定義標籤效果)

這裏寫圖片描述
上面是採用adapter模式實現的一個自定義標籤效果,傳入的是一個集合數據,同時可以靈活的設置標籤的背景以及給標籤設置相應的點擊事件。

代碼實現:

/**
 * Created by Administrator on 2017/7/3.
 * 流式佈局的適配器
 */

public abstract class TagAdapter {
    //有多少個條目
    public abstract int getCount();
    //getView通過position
    public abstract View getView(int position, ViewGroup parent);
    //觀察者模式通知更新
    public void unregisterDataSetObserver(DataSetObserver observer){

    };
    public void registerDataSetObserver(DataSetObserver observer){

    }
}
public class TagLayout extends ViewGroup {
    private List<List<View>> mChildViews = new ArrayList<>();
    private TagAdapter mAdapter;

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

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

    public TagLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 清空集合
        mChildViews.clear();

        int childCount = getChildCount();

        // 獲取到寬度
        int width = MeasureSpec.getSize(widthMeasureSpec);

        // 高度需要計算
        int height = getPaddingTop() + getPaddingBottom();

        // 一行的寬度
        int lineWidth = getPaddingLeft();

        ArrayList<View> childViews = new ArrayList<>();
        mChildViews.add(childViews);

        // 子View高度不一致的情況下
        int maxHeight = 0;

        for (int i = 0; i < childCount; i++) {

            // 2.1.1 for循環測量子View
            View childView = getChildAt(i);

            if(childView.getVisibility() == GONE){
                continue;
            }

            // 這段話執行之後就可以獲取子View的寬高,因爲會調用子View的onMeasure
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);

            // margin值 ViewGroup.LayoutParams 沒有 就用系統的MarginLayoutParams
            // 想想 LinearLayout爲什麼有?
            // LinearLayout有自己的 LayoutParams  會複寫一個非常重要的方法
            MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();

            // 什麼時候需要換行,一行不夠的情況下 考慮 margin
            if (lineWidth + (childView.getMeasuredWidth() + params.rightMargin + params.leftMargin) > width) {
                // 換行,累加高度  加上一行條目中最大的高度
                height += maxHeight;
                lineWidth = childView.getMeasuredWidth() + params.rightMargin + params.leftMargin;
                childViews = new ArrayList<>();
                mChildViews.add(childViews);
            } else {
                lineWidth += childView.getMeasuredWidth() + params.rightMargin + params.leftMargin;
                maxHeight = Math.max(childView.getMeasuredHeight() + params.bottomMargin + params.topMargin, maxHeight);
            }

            childViews.add(childView);
        }

        height += maxHeight;

        Log.e("TAG", "width -> " + width + " height-> " + height);
        // 2.1.2 根據子View計算和指定自己的寬高
        setMeasuredDimension(width, height);
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return super.generateLayoutParams(p);
    }

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

    /**
     * 擺放
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int left, top = getPaddingTop(), right, bottom;

        for (List<View> childViews : mChildViews) {
            left = getPaddingLeft();
            int maxHeight = 0;
            for (View childView : childViews) {

                if(childView.getVisibility() == GONE){
                    continue;
                }

                MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();
                left += params.leftMargin;
                int childTop = top + params.topMargin;
                right = left + childView.getMeasuredWidth();
                bottom = childTop + childView.getMeasuredHeight();
                Log.e("TAG", childView.toString());

                Log.e("TAG", "left -> " + left + " top-> " + childTop + " right -> " + right + " bottom-> " + bottom);

                // 擺放
                childView.layout(left, childTop, right, bottom);
                // left 疊加
                left += childView.getMeasuredWidth() + params.rightMargin;

                // 不斷的疊加top值
                int childHeight = childView.getMeasuredHeight()+ params.topMargin+params.bottomMargin;
                maxHeight = Math.max(maxHeight,childHeight);
            }

            top += maxHeight;
        }
    }
    public void setAdapter(TagAdapter adapter){
        if(adapter==null){
            //控制針異常
            throw new NullPointerException("adapter is null");
        }
        //清空所有子view
        removeAllViews();
        mAdapter=adapter;
        //獲取數量
        int childCount=mAdapter.getCount();
        for(int i=0;i<childCount;i++){
            View childView = mAdapter.getView(i,this);
            addView(childView);
        }
    }
}

這裏extends ViewGroup,其實自定義的TabLayout也就是一個佈局容器,這裏主要涉及到的就是字view的測量和擺放,所以肯定要重寫onMeasure和OnLayout,在測量和擺放的時要根據子view的情況去計算每行的高度和寬度,根據計算的寬度和父佈局的寬度進行對比是否要換行;經過測量和擺放後,差不多就實現了,在佈局文件中直接使用就可以了。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.viewday08.MainActivity">

    <com.viewday08.TagLayout
        android:id="@+id/tag_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.viewday08.TagLayout>
</LinearLayout>

獲取自定義的TagLayout並設置adapter

public class MainActivity extends AppCompatActivity {
    private TagLayout tagLayout;
    private List<String> mItems;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tagLayout = (TagLayout) findViewById(R.id.tag_layout);

        mItems=new ArrayList<>();
        mItems.add("111111111111111111111");
        mItems.add("222");
        mItems.add("3333333333");
        mItems.add("666677");
        mItems.add("000009989");
        mItems.add("1111111");
        mItems.add("222");
        mItems.add("3333333333");
        mItems.add("666677");
        mItems.add("000009989111111111111111111111");
        mItems.add("1111111");
        mItems.add("222");
        mItems.add("3333333333");
        mItems.add("666677");
        mItems.add("000009989");

        tagLayout.setAdapter(new TagAdapter() {
            @Override
            public int getCount() {
                return mItems.size();
            }

            @Override
            public View getView(int position, ViewGroup parent) {
                TextView tagTv = (TextView) LayoutInflater.from(MainActivity.this).inflate(R.layout.item_tag, parent, false);
                final String s = mItems.get(position);
                tagTv.setText(s);
                tagTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
                    }
                });
                return tagTv;
            }
        });
    }
}

這樣子效果就實現了。

源碼地址:
http://pan.baidu.com/s/1dF90eIl

發佈了80 篇原創文章 · 獲贊 32 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章