仿微信、QQ聊天表情底部弹出

前段时间学习了View的滑动以及Scroller的使用,正好项目中有聊天的功能,就仿照QQ聊天实现了,俗话说:好记性不如乱笔头,今天我们就来实战下。

实现效果

No picture say a xx,先看下效果图吧!
仿微信、QQ聊天表情底部弹出_第1张图片

效果实现

结合效果图,我们仔细分析一下,其实实现起来没那么难,主要逻辑就是控制底部view的弹出与显示。
1.首先我们自定义一个ViewGroup,并测量所有子view

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

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

    public EmojiKeyBoardLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScroller = new Scroller(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
    }

2.底部View的初始位置处于屏幕下方,我们在onLayout中对子View进行布局。

 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i if (i==0){
                contentView =child;
                //第一个childview,占满屏幕
                child.layout(0,0,child.getMeasuredWidth(),child.getMeasuredHeight());
            }else{
                bottomView =child;
                child.layout(0,contentView.getMeasuredHeight(),child.getMeasuredWidth(),contentView.getMeasuredHeight()+child.getMeasuredHeight());
            }
        }
    }

3.剩下的就是底部View弹出和显示操作实现了,我们使用Scroller来实现弹性滑动。

 public void showBottomView(){
        if (getScrollY()==0){
            hideKeyBoard();
            mScroller.startScroll(0,0,0,bottomView.getMeasuredHeight());
            invalidate();
        }
    }

    public void closeBottomView(){
        hideKeyBoard();
        mScroller.startScroll(0,getScrollY(),0,-getScrollY());
        invalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()){
            scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            postInvalidate();
        }
    }

核心代码就这么多,基本都是常规操作。读万卷书,不如行万里路,看代码再多,不实践的话,永远都是别人的代码

你可能感兴趣的:(仿微信、QQ聊天表情底部弹出)