Android开发探索Android DemoAndroid-自定义view

Android自定义View,访简书赞赏平放

2018-04-20  本文已影响635人  Sky_Blue
一、先看一下要实现的效果
简书效果图.jpg
公司UI效果图.jpg
二、自定义View的一般套路
1. 效果分析,自定义属性
2. 测量控件的宽高
3. 摆放控件的位置
4. 绘制控件
5. 用户交互(事件处理)
三、要实现的效果分析
  1. 简书上的效果是第二个View压在第一个上,依此类推
  2. 而公司给的效果是第一个压在第二个上,依此类推
  3. 就是两个View之间的间距公司给的UI挤一点,简书上的宽一些
四、根据效果分析自定义属性
<declare-styleable name="LineLayout">
    <!--两个View之间的间距 :值越小就越近,越大就越远-->
    <attr name="lineViewMarginRate" format="float" />
    <!--View的层次关系,true:前面的在上,false:后面的在上-->
    <attr name="lineIsReverse" format="boolean" />
</declare-styleable>
五、自定义ViewGroup,赞赏平放的布局,并找到自定义属性
/**
 * 访简书赞赏平放的布局
 */

public class LineLayout extends ViewGroup {
    /**
     * 两个View之间距的比例
     */
    private float mViewMarginRate = 0.5f;
    /**
     * 是不是从后面向前摆放
     */
    private boolean mIsReverse = true;


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

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

    public LineLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LineLayout);
        // 默认是在一半的位置
        mViewMarginRate = array.getFloat(R.styleable.LineLayout_lineViewMarginRate, mViewMarginRate);
        // 默认第一个在上面
        mIsReverse = array.getBoolean(R.styleable.LineLayout_lineIsReverse, mIsReverse);
        array.recycle();
    }
   
}
六、测量控件的宽高

先看一下摆放的示意图:


摆放示意图.jpg
  1. 控件的宽度上图可以得出

  2. 控件的高度就是子View的最高的那个的高度

     @Override
     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
         // 1.测量控件的宽高
         // 获取自已的测量模式
         int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
         int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
         // 获取自已的宽高
         int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
         int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    
         int count = getChildCount();
         int height = 0;
         int width = 0;
    
         for (int i = 0; i < count; i++) {
             View child = getChildAt(i);
             measureChild(child, widthMeasureSpec, heightMeasureSpec);
             int measuredWidth = child.getMeasuredWidth();
             // 计算控件的宽度
             if (i == 0) {
                 width = measuredWidth;
             } else {
                 width += (int) (mViewMarginRate * width + 0.5f);
             }
             int measuredHeight = child.getMeasuredHeight();
             // 高度取最大的子View的高度
             height = Math.max(height, measuredHeight);
         }
         width += getPaddingLeft() + getPaddingRight();
         height += getPaddingTop() + getPaddingBottom();
         // 设置自己的宽高
         setMeasuredDimension
                 (
                         modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                         modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height
                 );
    
    
     }
    
七、摆放子View

摆放很简单,从(0,0,childWidth,childHeight)开始。
第二个子View的左边开始位置就是叠加左边的间距。

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            int count = getChildCount();
            int cl = getPaddingLeft();
            int ct = getPaddingTop();
            // 摆放
            for (int i = 0; i < count; i++) {
                View child = getChildAt(i);
                int width = child.getMeasuredWidth();
                int height = child.getMeasuredHeight();
                if (i > 0) {
                    // 计算第二个后面子View左边的位置
                    cl += (int) (mViewMarginRate * width + 0.5f);
                }
                // 摆放子View
                child.layout(cl, ct, cl + width, ct + height);
            }
        }
    }
八、怎么样让前面的View压后面的View
  1. 设置充许改变绘制顺序:setChildrenDrawingOrderEnabled(true);

  2. 复写getChildDrawingOrder这个方法

     @Override
     protected int getChildDrawingOrder(int childCount, int i) {
         // 确定View的绘制优先级
         if (!mIsReverse) {
             return i;
         }
         return childCount - 1 - i;
     }
    
九、方便使用,引入Adapter设置模式
    public abstract class LineAdapter {
        private DataSetObservable mObservable = new DataSetObservable();

        /**
         * 数量
         */
        public abstract int getCount();

        /**
         * 条目的布局
         */
        public abstract View getView(int position, ViewGroup parent);

        /**
         * 注册数据监听
         */
        public void registerDataSetObserver(DataSetObserver observer) {
            mObservable.registerObserver(observer);
        }

        /**
         * 移除数据监听
         */
        public void unregisterDataSetObserver(DataSetObserver observer) {
            mObservable.unregisterObserver(observer);
        }

        /**
         * 内容改变
         */
        public void notifyDataSetChanged() {
            mObservable.notifyChanged();
        }

    }
十、完整代码的编写
/**
 * 访简书赞赏平放的布局
 */

public class LineLayout extends ViewGroup {
    /**
     * 两个View之间距的比例
     */
    private float mViewMarginRate = 0.5f;
    /**
     * 是不是从后面向前摆放
     */
    private boolean mIsReverse = true;


    private LineAdapter mAdapter;
    private DataSetObserver mObserver;

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

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

    public LineLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LineLayout);
        // 默认是在一半的位置
        mViewMarginRate = array.getFloat(R.styleable.LineLayout_lineViewMarginRate, mViewMarginRate);
        // 默认第一个在上面
        mIsReverse = array.getBoolean(R.styleable.LineLayout_lineIsReverse, mIsReverse);
        array.recycle();

    // 设置充许改变绘制顺序
    setChildrenDrawingOrderEnabled(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // 1.测量控件的宽高
        // 获取自已的测量模式
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
        // 获取自已的宽高
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        int count = getChildCount();
        int height = 0;
        int width = 0;

        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            int measuredWidth = child.getMeasuredWidth();
            // 计算控件的宽度
            if (i == 0) {
                width = measuredWidth;
            } else {
                width += (int) (mViewMarginRate * width + 0.5f);
            }
            int measuredHeight = child.getMeasuredHeight();
            // 高度取最大的子View的高度
            height = Math.max(height, measuredHeight);
        }
        width += getPaddingLeft() + getPaddingRight();
        height += getPaddingTop() + getPaddingBottom();
        // 设置自己的宽高
        setMeasuredDimension
                (
                        modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
                        modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height
                );


    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            int count = getChildCount();
            int cl = getPaddingLeft();
            int ct = getPaddingTop();
            // 摆放
            for (int i = 0; i < count; i++) {
                View child = getChildAt(i);
                int width = child.getMeasuredWidth();
                int height = child.getMeasuredHeight();
                if (i > 0) {
                    // 计算第二个后面子View左边的位置
                    cl += (int) (mViewMarginRate * width + 0.5f);
                }
                // 摆放子View
                child.layout(cl, ct, cl + width, ct + height);
            }
        }
    }



    /**
     * 设置Adapter
     */
    public void setAdapter(LineAdapter adapter) {
        // 移除监听
        if (mAdapter != null && mObserver != null) {
            mAdapter.unregisterDataSetObserver(mObserver);
            mAdapter = null;
            mObserver = null;
        }
        if (adapter == null) {
            throw new NullPointerException("FlowBaseAdapter is null");
        }
        mAdapter = adapter;
        resetLayout();
        mObserver = new DataSetObserver() {
            @Override
            public void onChanged() {
                resetLayout();
            }
        };
        mAdapter.registerDataSetObserver(mObserver);

    }

    /**
     * 重新添加布局
     */
    private void resetLayout() {
        removeAllViews();
        int count = mAdapter.getCount();
        for (int i = 0; i < count; i++) {
            View view = mAdapter.getView(i, this);
            addView(view);
        }
    }
@Override
protected int getChildDrawingOrder(int childCount, int i) {
    // 确定View的绘制优先级
    if (!mIsReverse) {
        return i;
    }
    return childCount - 1 - i;
}

    @Override
    protected void onDetachedFromWindow() {
        // 移除监听
        if (mAdapter != null && mObserver != null) {
            mAdapter.unregisterDataSetObserver(mObserver);
            mAdapter = null;
            mObserver = null;

        }
        super.onDetachedFromWindow();
    }
}
十一、测试代码
  1. 测试的布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.wen.routerdemo.view.LineLayout xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/line_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        app:lineViewMarginRate="0.7" />

</FrameLayout>
  1. 测试Activity的代码
/**
 * 测试类
 */
public class LineLayoutActivity extends AppActivity {
    private LineLayout mLineLayout;

    @Override
    protected Object getContentLayout() {
        return R.layout.activity_line_layout;
    }

    @Override
    protected void initView(View contentView) {
        mLineLayout = findViewById(R.id.line_layout);
        mLineLayout.setAdapter(new LineAdapter() {
            @Override
            public int getCount() {
                return 8;
            }

            @Override
            public View getView(final int position, ViewGroup parent) {
                ImageView imageView = new ImageView(parent.getContext());
                imageView.setImageResource(R.mipmap.ic_launcher_round);
                if (position == 0) {
                    imageView.setImageResource(R.mipmap.ic_launcher);
                }
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(LineLayoutActivity.this, "position--" + position, Toast.LENGTH_SHORT).show();
                    }
                });
                return imageView;
            }
        });
    }
}
十二、最后测试效果图
测试效果图.jpg

就这么个小玩意,搞了四个小时,喜欢的点个赞。

上一篇下一篇

猜你喜欢

热点阅读