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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值