自定义一个类似listView和recylceView的需要setAdapter的控件

package com.tddapp.main.common.customview;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.tddapp.main.R;

/**
 * @author: xiaolijuan
 * @description: 流式布局-标签流容器
 * @projectName: FlowLayoutDome
 * @date: 2016-06-16
 * @time: 16:21
 */
public class FlowLayout extends ViewGroup{
    /**
     * 每个item纵向间距
     */
    private int mVerticalSpacing;
    /**
     * 每个item横向间距
     */
    private int mHorizontalSpacing;
    private BaseAdapter mAdapter;
    private TagItemClickListener mListener;
    private DataChangeObserver mObserver;

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

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

    public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        /**
         * 获得我们所定义的自定义样式属性
         */
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.FlowLayout, defStyle, 0);
        int index = a.getIndexCount();
        for (int i = 0; i < index; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.FlowLayout_verticalSpacing:
                    mVerticalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_verticalSpacing, 50);
                    break;
                case R.styleable.FlowLayout_horizontalSpacing:
                    mHorizontalSpacing = a.getDimensionPixelSize(R.styleable.FlowLayout_horizontalSpacing, 100);
                    break;
            }
        }
        a.recycle();
    }

    /**
     * 负责设置子控件的测量模式和大小 根据所有子控件设置自己的宽和高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        /**
         * 默认宽为父容器为它设置的测量宽度
         */
        int width = MeasureSpec.getSize(widthMeasureSpec);
        /**
         * 高
         */
        int height = 0;
        /**
         * 每一行的高度,累加至height
         */
        int lineHeight = 0;
        /**
         * 在warp_content情况下,记录当前childView的左边的一个位置
         */
        int childLeft = getPaddingLeft();
        /**
         * 在warp_content情况下,记录当前childView的上边的一个位置
         */
        int childTop = getPaddingTop();
        // getChildCount得到子view的数目,遍历循环出每个子View
        for (int i = 0; i < getChildCount(); i++) {
            //拿到index上的子view
            View childView = getChildAt(i);
            // 测量每一个child的宽和高
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            //当前子空间实际占据的高度
            int childHeight = childView.getMeasuredHeight();
            //当前子空间实际占据的宽度
            int childWidth = childView.getMeasuredWidth();
            lineHeight = Math.max(childHeight, lineHeight);// 取最大值
            //如果加入当前childView,超出最大宽度,则将目前最大宽度给width,类加height 然后开启新行
            if (childWidth + childLeft + getPaddingRight() > width) {
                childLeft = getPaddingLeft();// 重新开启新行,开始记录childLeft
                childTop += mVerticalSpacing + childHeight;// 叠加当前的高度
                lineHeight = childHeight;// 开启记录下一行的高度
            }else{
                //否则累加当前childView的宽度
                childLeft += childWidth + mHorizontalSpacing;
            }
        }
        height += childTop + lineHeight + getPaddingBottom();
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int width = r - l;
        int childLeft = getPaddingLeft();
        int childTop = getPaddingTop();
        int lineHeight = 0;
        //遍历所有childView根据其宽和高,计算子控件应该出现的位置
        for (int i = 0; i < getChildCount(); i++) {
            final View childView = getChildAt(i);
            if (childView.getVisibility() == View.GONE) {
                continue;
            }
            int childWidth = childView.getMeasuredWidth();
            int childHeight = childView.getMeasuredHeight();
            lineHeight = Math.max(childHeight, lineHeight);
            // 如果已经需要换行
            if (childLeft + childWidth + getPaddingRight() > width) {
                childLeft = getPaddingLeft();
                childTop += mVerticalSpacing + lineHeight;
                lineHeight = childHeight;
            }
            childView.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
            childLeft += childWidth + mHorizontalSpacing;
        }
    }

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

    private void drawLayout() {
        if (mAdapter == null || mAdapter.getCount() == 0) {
            return;
        }
        removeAllViews();
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View view = mAdapter.getView(i, null, null);
            final int position = i;
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.itemClick(position,mAdapter.getItem(position));
                    }
                }
            });
            addView(view);
        }
    }

    public void setAdapter(BaseAdapter adapter) {
        if (mAdapter == null) {
            mAdapter = adapter;
            if (mObserver == null) {
                mObserver = new DataChangeObserver();
                mAdapter.registerDataSetObserver(mObserver);
            }
            drawLayout();
        }
    }

    public void setItemClickListener(TagItemClickListener mListener) {
        this.mListener = mListener;
    }

    public interface TagItemClickListener {
        void itemClick(int position,Object bean);
    }

    class DataChangeObserver extends DataSetObserver {
        @Override
        public void onChanged() {
            drawLayout();
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    }
}    

==========================================================================                                                                                                                                                        
我的理解:这种类似listview的控件就是一个ViewGroup,给里面添加一个个的子View。读取list数据,然后通过一个DataSetObserver来观察list这个数组的变化,如果发生了变化就会调用drawLayout重绘子View。所以Adapter的重点就是使用DataSetObserver。当然listView除了这个基础的原理,里面还有复用的处理。

==========================================================================

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import com.tddapp.main.R;
import com.tddapp.main.module.bean.ApplyAfterFee;

import java.util.List;

/**
 * @author: adan
 * @description: 流式布局适配器
 * @projectName: FlowLayoutDome
 * @date: 2016-06-16
 * @time: 16:22
 */
public class FlowLayoutAdapter extends BaseAdapter {

    private Context mContext;
    private List<ApplyAfterFee.ReasonsBean> mList;

    public FlowLayoutAdapter(Context context, List<ApplyAfterFee.ReasonsBean> list) {
        mContext = context;
        mList = list;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public ApplyAfterFee.ReasonsBean getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.item_tag, null);
            holder = new ViewHolder();
            holder.mBtnTag = (Button) convertView.findViewById(R.id.btn_tag);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.mBtnTag.setText(getItem(position).getLabel());
        return convertView;
    }

    static class ViewHolder {
        Button mBtnTag;
    }
}
使用:
  mHotLabelAdapter = new FlowLayoutAdapter(ApplyAfterSalesActivity.this, fee.getReasons());
  flowLayout.setAdapter(mHotLabelAdapter);
  flowLayout.setItemClickListener(new TagItemClickListener(){});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值