Android自定義View--用ViewGroup打造一個3D堆疊卡片容器

1. 功能描述

目前只能支持三張圖片认轨,支持橫豎屏模式绅络,手指滑動翻頁到下一張卡片,手指點擊也可以切換到當前卡片嘁字,并且選中的卡片會在整個ViewGroup的最上層恩急,會被放大,可以自定義放大動畫的時長纪蜒。最基本的Android自定義控件衷恭,大神就別看了。
來先看效果圖吧:
支持豎屏模式

gif

也支持橫屏模式:
gif2

屬性 描述 默認值
scc_anim_duration 卡片放大動畫時間 300
scc_edge 每個卡片頂邊和底邊的距離 60
scc_type 豎屏還是橫屏模式 VERTICAL
scc_min_change_distance 手指最小滑動距離才會翻頁 20

主要是想熟悉一下自定義控件的基本測量和布局方式纯续,其實使用LinearLayout或者是FrameLayout來做會更加方便随珠,但是這個時候就不需要我們自己去重寫onMeasure和onLayout方法了。
支持的自定義屬性:

屬性 描述 默認值
scc_anim_duration 卡片放大動畫時間 300
scc_edge 每個卡片頂邊和底邊的距離 60
scc_type 豎屏還是橫屏模式 VERTICAL
scc_min_change_distance 手指最小滑動距離才會翻頁 20

2. 實現(xiàn)原理

把ViewGroup中的三個View(可為任意的三個控件)按照預設好的邊距和padding測量大小杆烁,然后三個view根據(jù)edge值來確定依次確定位置牙丽。我們沒有用到canvas、path或者paint兔魂。沒必要,我們只需要改變子View的繪制順序举娩,檢測到用戶的滑動或者是點擊就invalidate重繪析校,把用戶選中的view放在最后繪制這樣就可以將當前選中的view放在最上層构罗。這樣放大選中的view就不會被遮住。


原理

3. 代碼講解

a. 改變子View的繪制次序

    /**
     * 獲取子控件dispatchDraw的次序智玻,將當前選中的View放在最后繪制
     */
    @Override
    protected int getChildDrawingOrder(int childCount, int i) {
    //currentItemIndex 為當前選中的View在ViewGroup中的position
        if (currentItemIndex < 0) {
            return i;
        }
        if (i < (childCount - 1)) {
            if (currentItemIndex == i)
                i = childCount - 1;
        } else {
            if (currentItemIndex < childCount)
                i = currentItemIndex;
        }
        return i;
    }

b. 測量子View大小

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /**
         * 獲得此ViewGroup上級容器為其推薦的寬和高遂唧,以及計算模式
         */
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);

        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        /**
         * 先測量整個Viewgroup的大小
         */
        setMeasuredDimension(sizeWidth, sizeHeight);

        int childCount = getChildCount();
        int childWidth, childHeight;
        /**由于每一個子View的寬高都是一樣的所以就一起計算每一個View的寬高*/
        if(ShapeType.VERTICAL.ordinal() == mShapeType){  //豎向模式
            childWidth = getMeasuredWidth() - padding*2;
            childHeight = getMeasuredHeight() - padding*2 - edge*2;
        }else{   //橫向模式
            childWidth = getMeasuredWidth() - padding*2 - edge*2;
            childHeight = getMeasuredHeight() - padding*2;
        }

        int childWidthMeasureSpec = 0;
        int childHeightMeasureSpec = 0;

        // 循環(huán)測量每一個View
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);

            // 系統(tǒng)自動測量子View:
//            measureChild(childView, widthMeasureSpec, heightMeasureSpec);

            /** 以一個精確值來測量子View的寬度 */
            childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidth, MeasureSpec.EXACTLY);
            childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeight, MeasureSpec.EXACTLY);
            childView.measure(childWidthMeasureSpec,childHeightMeasureSpec);
        }

    }

c. 測量子View位置

位置確定最基本原理:


onlayout
@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        // 循環(huán)測量每一個View
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            //四個方向的margin值
            int measureL = 0, measurelT = 0, measurelR = 0, measurelB = 0;

            if(ShapeType.VERTICAL.ordinal() == mShapeType){  //豎向模式
                switch (i){
                    case 0:
                        measureL = padding;
                        measurelT = padding;
                        measurelB = childView.getMeasuredHeight() + padding;
                        measurelR = childView.getMeasuredWidth() + padding;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                    case 1:
                        measureL = padding;
                        measurelT = padding + edge;
                        measurelB = childView.getMeasuredHeight() + padding + edge;
                        measurelR = childView.getMeasuredWidth() + padding;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                    case 2:
                        measureL = padding;
                        measurelT = padding + edge*2;
                        measurelB = childView.getMeasuredHeight() + padding + edge*2;
                        measurelR = childView.getMeasuredWidth() + padding;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                }
            }else{   //橫向模式
                switch (i){
                    case 0:
                        measureL = padding;
                        measurelT = padding;
                        measurelB = childView.getMeasuredHeight() + padding;
                        measurelR = childView.getMeasuredWidth() + padding;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                    case 1:
                        measureL = padding + edge;
                        measurelT = padding;
                        measurelB = childView.getMeasuredHeight() + padding;
                        measurelR = childView.getMeasuredWidth() + padding + edge;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                    case 2:
                        measureL = padding + edge*2;
                        measurelT = padding;
                        measurelB = childView.getMeasuredHeight() + padding;
                        measurelR = childView.getMeasuredWidth() + padding + edge*2;
                        childView.layout(measureL, measurelT, measurelR, measurelB);
                        break;
                }
            }


        }
    }

d. 手勢交互邏輯

在手指滑動的時候為了防止頻繁觸發(fā)翻頁,我使用了handler去發(fā)送翻頁消息吊奢。

    /**
     * 事件分發(fā)
     * onTouchEvent() 用于處理事件盖彭,返回值決定當前控件是否消費(consume)了這個事件
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d("danxx", "onTouchEvent");
//        return super.onTouchEvent(event);
        /**以屏幕左上角為坐標原點計算的Y軸坐標**/
        int y;
        if(ShapeType.VERTICAL.ordinal() ==  mShapeType){ //豎屏模式取Y軸坐標
            y = (int) event.getRawY();
        }else{
            y = (int) event.getRawX(); //橫屏模式取X軸坐標
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i(TAG, "MotionEvent.ACTION_DOWN");
                // 手指按下時記錄下y坐標
                lastY = y;
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TAG, "MotionEvent.ACTION_MOVE");
                // 手指向下滑動時 y坐標 = 屏幕左上角為坐標原點計算的Y軸坐標 - 手指滑動的Y軸坐標
                int m = y - lastY;
                if(m>0 && m>changeDistance){  //手指向下滑動 或者是左滑
                    changeHandler.removeMessages(MSG_UP);
                    changeHandler.sendEmptyMessageDelayed(MSG_UP, animDuration);

                }else if(m< 0&& Math.abs(m)>changeDistance){ //手指向上滑動 或者右滑
                    changeHandler.removeMessages(MSG_DOWN);
                    changeHandler.sendEmptyMessageDelayed(MSG_DOWN, animDuration);
                }

                // 記錄下此刻y坐標
                this.lastY = y;
                break;
            case MotionEvent.ACTION_UP:
                Log.i(TAG, "MotionEvent.ACTION_UP");
                break;
        }
        return true;
    }

d. 上下或者左右翻頁代碼

    /**
     * 顯示下面的一頁
     * 翻頁成功返回true,否則false
     */
    private boolean downPage(){
        if(1 == currentItemIndex){
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), false, 1.0f, animDuration);
            // 重繪页滚,改變堆疊順序
            currentItemIndex = 2;
            postInvalidate();
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), true, 1.06f, animDuration);
            return true;
        }else if(0 == currentItemIndex){
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), false, 1.0f, animDuration);
            // 重繪召边,改變堆疊順序
            currentItemIndex = 1;
            postInvalidate();
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), true, 1.06f, animDuration);
            return true;
        }else if(2 == currentItemIndex){
            return false;
        }
        return false;
    }

    /**
     * 顯示上面的一頁
     * 翻頁成功返回true,否則false
     */
    private boolean upPage(){
        if(1 == currentItemIndex){
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), false, 1.0f, animDuration);
            // 重繪裹驰,改變堆疊順序
            currentItemIndex = 0;
            postInvalidate();
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), true, 1.06f, animDuration);
            return true;
        }else if(0 == currentItemIndex){
            return false;
        }else if(2 == currentItemIndex){
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), false, 1.0f, animDuration);
            currentItemIndex = 1;
            postInvalidate();
            FocusAnimUtils.animItem(getChildAt(currentItemIndex), true, 1.06f, animDuration);
            return true;
        }
        return false;
    }

4. xml布局文件

<?xml version="1.0" encoding="utf-8"?>
<danxx.library.widget.StackCardContainer xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/threeDViewContainer"
    app:scc_anim_duration="300"
    app:scc_edge="90"
    app:scc_padding="70"
    app:scc_type="horizontal"
    app:scc_min_change_distance="20"
    android:layout_margin="10dp"
    android:layout_width="match_parent"
    android:layout_height="420dp">

    <android.support.v7.widget.CardView
        android:id="@+id/view1"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@mipmap/card_view_bg0"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:text="血戰(zhàn)鋼鋸嶺"
            android:padding="6dp"
            android:textSize="22sp"
            android:lines="1"
            android:gravity="center"
            android:layout_gravity="bottom"
            android:background="#CAC26F"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/view2"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@mipmap/card_view_bg1"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:text="你的名字"
            android:padding="6dp"
            android:textSize="22sp"
            android:gravity="center"
            android:lines="1"
            android:layout_gravity="bottom"
            android:background="#0085BA"/>
    </android.support.v7.widget.CardView>

    <android.support.v7.widget.CardView
        android:id="@+id/view3"
        app:cardCornerRadius="10dp"
        app:cardElevation="10dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="centerCrop"
            android:src="@mipmap/card_view_bg2"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:text="從你的全世界路過"
            android:lines="1"
            android:padding="6dp"
            android:textSize="22sp"
            android:gravity="center"
            android:layout_gravity="bottom"
            android:background="#4EC9AD"/>
    </android.support.v7.widget.CardView>

</danxx.library.widget.StackCardContainer>

其實就是在我們自定義的StackCardContainer容器中放置了三個CardView隧熙,至于點擊事件和數(shù)據(jù)綁定等完全由用戶自己去設置和綁定。StackCardContainer自定義控件只是改變了子View的布局方式并處理手勢交互罷了幻林。

5. 源代碼 : GitHub項目地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末贞盯,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子沪饺,更是在濱河造成了極大的恐慌躏敢,老刑警劉巖,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件整葡,死亡現(xiàn)場離奇詭異父丰,居然都是意外死亡,警方通過查閱死者的電腦和手機掘宪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進店門蛾扇,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人魏滚,你說我怎么就攤上這事镀首》乇龋” “怎么了涮雷?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長啸如。 經常有香客問我腥寇,道長成翩,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任赦役,我火速辦了婚禮麻敌,結果婚禮上,老公的妹妹穿的比我還像新娘掂摔。我一直安慰自己术羔,他們只是感情好赢赊,可當我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著级历,像睡著了一般释移。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上寥殖,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天玩讳,我揣著相機與錄音,去河邊找鬼嚼贡。 笑死熏纯,一個胖子當著我的面吹牛,可吹牛的內容都是我干的编曼。 我是一名探鬼主播豆巨,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼掐场!你這毒婦竟也來了往扔?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤熊户,失蹤者是張志新(化名)和其女友劉穎萍膛,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嚷堡,經...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡蝗罗,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蝌戒。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片串塑。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖北苟,靈堂內的尸體忽然破棺而出桩匪,到底是詐尸還是另有隱情,我是刑警寧澤友鼻,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布傻昙,位于F島的核電站,受9級特大地震影響彩扔,放射性物質發(fā)生泄漏妆档。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一虫碉、第九天 我趴在偏房一處隱蔽的房頂上張望贾惦。 院中可真熱鬧,春花似錦、人聲如沸纤虽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽逼纸。三九已至,卻和暖如春济蝉,著一層夾襖步出監(jiān)牢的瞬間杰刽,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工王滤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留贺嫂,地道東北人。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓雁乡,卻偏偏與公主長得像第喳,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子踱稍,可洞房花燭夜當晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,182評論 25 707
  • 內容抽屜菜單ListViewWebViewSwitchButton按鈕點贊按鈕進度條TabLayout圖標下拉刷新...
    皇小弟閱讀 46,767評論 22 665
  • 第一步:試探性發(fā)問 很多營銷人員曲饱、微商,這一步做錯了珠月。 一上來就是介紹自己的產品扩淀,說自己產品多么多么NB。然后客戶...
    熊芳菲閱讀 734評論 0 0
  • 有的時候沒有成功只是的方法不對啤挎,而不是還不夠努力驻谆。 我很喜歡這句心靈砒霜“但凡努力了就可以成功,那么還會有這么多人...
    城中聽雨閱讀 732評論 1 12
  • 哈德遜河畔鋪滿紅葉 肥碩的鴿子壓彎路燈 云朵好像豆腐腦 把我們裝在碗里 苦悶的人兒抬頭看云 想問它是咸是甜 云兒默...
    十號公路閱讀 297評論 1 10