Android自定義View——從零開始實現可展開收起的水平選單欄

Anlia發表於2017-12-23

版權宣告:本文為博主原創文章,未經博主允許不得轉載

系列教程:Android開發之從零開始系列

原始碼:AnliaLee/ExpandMenu,歡迎star

大家要是看到有錯誤的地方或者有啥好的建議,歡迎留言評論

前言:最近專案裡要實現一個 可展開收起的水平選單欄控制元件,剛接到需求時想著用自定義View自己來繪製,發現要實現 圓角、陰影、選單滑動等效果非常複雜且耗時間。好在這些效果 Android原生程式碼中都已經有非常成熟的解決方案,我們只需要去繼承它們進行 二次開發就行。本期將教大家如何 繼承ViewGroup(RelativeLayout)實現自定義選單欄

本篇只著重於思路和實現步驟,裡面用到的一些知識原理不會非常細地拿來講,如果有不清楚的api或方法可以在網上搜下相應的資料,肯定有大神講得非常清楚的,我這就不獻醜了。本著認真負責的精神我會把相關知識的博文連結也貼出來(其實就是懶不想寫那麼多哈哈),大家可以自行傳送。為了照顧第一次閱讀系列部落格的小夥伴,本篇會出現一些在之前系列部落格就講過的內容,看過的童鞋自行跳過該段即可

國際慣例,先上效果圖

Android自定義View——從零開始實現可展開收起的水平選單欄


為選單欄設定背景

自定義ViewGroup自定義View的繪製過程有所不同,View可以直接在自己的onDraw方法中繪製所需要的效果,而ViewGroup會先測量子View的大小位置(onLayout),然後再進行繪製,如果子View或background為空,則不會呼叫draw方法繪製。當然我們可以呼叫setWillNotDraw(false)ViewGroup可以在子View或background為空的情況下進行繪製,但我們會為ViewGroup設定一個預設背景,所以可以省去這句程式碼

設定背景很簡單,因為要實現圓角、描邊等效果,所以我們選擇使用GradientDrawable來定製背景,然後呼叫setBackground方法設定背景。建立HorizontalExpandMenu,繼承自RelativeLayout,同時自定義Attrs屬性

public class HorizontalExpandMenu extends RelativeLayout {
    private Context mContext;
    private AttributeSet mAttrs;

    private int defaultWidth;//預設寬度
    private int defaultHeight;//預設長度
    private int viewWidth;
    private int viewHeight;

    private int menuBackColor;//選單欄背景色
    private float menuStrokeSize;//選單欄邊框線的size
    private int menuStrokeColor;//選單欄邊框線的顏色
    private float menuCornerRadius;//選單欄圓角半徑

    public HorizontalExpandMenu(Context context) {
        super(context);
        this.mContext = context;
        init();
    }

    public HorizontalExpandMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        this.mAttrs = attrs;
        init();
    }

    private void init(){
        TypedArray typedArray = mContext.obtainStyledAttributes(mAttrs, R.styleable.HorizontalExpandMenu);

        defaultWidth = DpOrPxUtils.dip2px(mContext,200);
        defaultHeight = DpOrPxUtils.dip2px(mContext,40);

        menuBackColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_back_color,Color.WHITE);
        menuStrokeSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_stroke_size,1);
        menuStrokeColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_stroke_color,Color.GRAY);
        menuCornerRadius = typedArray.getDimension(R.styleable.HorizontalExpandMenu_corner_radius,DpOrPxUtils.dip2px(mContext,20));
        typedArray.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = measureSize(defaultHeight, heightMeasureSpec);
        int width = measureSize(defaultWidth, widthMeasureSpec);
        viewHeight = height;
        viewWidth = width;
        setMeasuredDimension(viewWidth,viewHeight);

        //佈局程式碼中如果沒有設定background屬性則在此處新增一個背景
        if(getBackground()==null){
            setMenuBackground();
        }
    }

    private int measureSize(int defaultSize, int measureSpec) {
        int result = defaultSize;
        int specMode = View.MeasureSpec.getMode(measureSpec);
        int specSize = View.MeasureSpec.getSize(measureSpec);

        if (specMode == View.MeasureSpec.EXACTLY) {
            result = specSize;
        } else if (specMode == View.MeasureSpec.AT_MOST) {
            result = Math.min(result, specSize);
        }
        return result;
    }

    /**
     * 設定選單背景,如果要顯示陰影,需在onLayout之前呼叫
     */
    private void setMenuBackground(){
        GradientDrawable gd = new GradientDrawable();
        gd.setColor(menuBackColor);
        gd.setStroke((int)menuStrokeSize, menuStrokeColor);
        gd.setCornerRadius(menuCornerRadius);
        setBackground(gd);
    }
}
複製程式碼

attrs屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--注意這裡的name要和自定義View的名稱一致,不然在xml佈局中無法引用-->
    <declare-styleable name="HorizontalExpandMenu">
        <attr name="back_color" format="color"></attr>
        <attr name="stroke_size" format="dimension"></attr>
        <attr name="stroke_color" format="color"></attr>
        <attr name="corner_radius" format="dimension"></attr>
    </declare-styleable>
</resources>
複製程式碼

在佈局檔案中使用

<com.anlia.expandmenu.widget.HorizontalExpandMenu
	android:id="@+id/expandMenu1"
	android:layout_width="match_parent"
	android:layout_height="40dp"
	android:layout_alignParentBottom="true"
	android:layout_marginBottom="20dp"
	android:layout_marginLeft="15dp"
	android:layout_marginRight="15dp">
</com.anlia.expandmenu.widget.HorizontalExpandMenu>
複製程式碼

效果如圖

Android自定義View——從零開始實現可展開收起的水平選單欄


繪製選單欄按鈕

我們要繪製選單欄兩邊的按鈕,首先是要為按鈕圈地(測量位置和大小)。設定按鈕區域為正方形,位於左側或右側(根據開發者設定而定)邊長和選單欄ViewGroup的高相等。按鈕中的加號可以使用Path進行繪製(當然也可以用向量圖點陣圖),程式碼如下

public class HorizontalExpandMenu extends RelativeLayout {
	//省略部分程式碼...
    private float buttonIconDegrees;//按鈕icon符號豎線的旋轉角度
    private float buttonIconSize;//按鈕icon符號的大小
    private float buttonIconStrokeWidth;//按鈕icon符號的粗細
    private int buttonIconColor;//按鈕icon顏色

    private int buttonStyle;//按鈕型別
    private int buttonRadius;//按鈕矩形區域內圓半徑
    private float buttonTop;//按鈕矩形區域top值
    private float buttonBottom;//按鈕矩形區域bottom值

    private Point rightButtonCenter;//右按鈕中點
    private float rightButtonLeft;//右按鈕矩形區域left值
    private float rightButtonRight;//右按鈕矩形區域right值

    private Point leftButtonCenter;//左按鈕中點
    private float leftButtonLeft;//左按鈕矩形區域left值
    private float leftButtonRight;//左按鈕矩形區域right值

    /**
     * 根按鈕所在位置,預設為右邊
     */
    public class ButtonStyle {
        public static final int Right = 0;
        public static final int Left = 1;
    }

    private void init(){
		//省略部分程式碼...
        buttonStyle = typedArray.getInteger(R.styleable.HorizontalExpandMenu_button_style,ButtonStyle.Right);
        buttonIconDegrees = 0;
        buttonIconSize = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_size,DpOrPxUtils.dip2px(mContext,8));
        buttonIconStrokeWidth = typedArray.getDimension(R.styleable.HorizontalExpandMenu_button_icon_stroke_width,8);
        buttonIconColor = typedArray.getColor(R.styleable.HorizontalExpandMenu_button_icon_color,Color.GRAY);

        buttonIconPaint = new Paint();
        buttonIconPaint.setColor(buttonIconColor);
        buttonIconPaint.setStyle(Paint.Style.STROKE);
        buttonIconPaint.setStrokeWidth(buttonIconStrokeWidth);
        buttonIconPaint.setAntiAlias(true);

        path = new Path();
        leftButtonCenter = new Point();
        rightButtonCenter = new Point();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = measureSize(defaultHeight, heightMeasureSpec);
        int width = measureSize(defaultWidth, widthMeasureSpec);
        viewHeight = height;
        viewWidth = width;
        setMeasuredDimension(viewWidth,viewHeight);

        buttonRadius = viewHeight/2;
        layoutRootButton();

        //佈局程式碼中如果沒有設定background屬性則在此處新增一個背景
        if(getBackground()==null){
            setMenuBackground();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        layoutRootButton();
        if(buttonStyle == ButtonStyle.Right){
            drawRightIcon(canvas);
        }else {
            drawLeftIcon(canvas);
        }

        super.onDraw(canvas);//注意父方法在最後呼叫,以免icon被遮蓋
    }

    /**
     * 測量按鈕中點和矩形位置
     */
    private void layoutRootButton(){
        buttonTop = 0;
        buttonBottom = viewHeight;

        rightButtonCenter.x = viewWidth- buttonRadius;
        rightButtonCenter.y = viewHeight/2;
        rightButtonLeft = rightButtonCenter.x- buttonRadius;
        rightButtonRight = rightButtonCenter.x+ buttonRadius;

        leftButtonCenter.x = buttonRadius;
        leftButtonCenter.y = viewHeight/2;
        leftButtonLeft = leftButtonCenter.x- buttonRadius;
        leftButtonRight = leftButtonCenter.x+ buttonRadius;
    }

    /**
     * 繪製左邊的按鈕
     * @param canvas
     */
    private void drawLeftIcon(Canvas canvas){
        path.reset();
        path.moveTo(leftButtonCenter.x- buttonIconSize, leftButtonCenter.y);
        path.lineTo(leftButtonCenter.x+ buttonIconSize, leftButtonCenter.y);
        canvas.drawPath(path, buttonIconPaint);//劃橫線

        canvas.save();
        canvas.rotate(-buttonIconDegrees, leftButtonCenter.x, leftButtonCenter.y);//旋轉畫布,讓豎線可以隨角度旋轉
        path.reset();
        path.moveTo(leftButtonCenter.x, leftButtonCenter.y- buttonIconSize);
        path.lineTo(leftButtonCenter.x, leftButtonCenter.y+ buttonIconSize);
        canvas.drawPath(path, buttonIconPaint);//畫豎線
        canvas.restore();
    }

    /**
     * 繪製右邊的按鈕
     * @param canvas
     */
    private void drawRightIcon(Canvas canvas){
        path.reset();
        path.moveTo(rightButtonCenter.x- buttonIconSize, rightButtonCenter.y);
        path.lineTo(rightButtonCenter.x+ buttonIconSize, rightButtonCenter.y);
        canvas.drawPath(path, buttonIconPaint);//劃橫線

        canvas.save();
        canvas.rotate(buttonIconDegrees, rightButtonCenter.x, rightButtonCenter.y);//旋轉畫布,讓豎線可以隨角度旋轉
        path.reset();
        path.moveTo(rightButtonCenter.x, rightButtonCenter.y- buttonIconSize);
        path.lineTo(rightButtonCenter.x, rightButtonCenter.y+ buttonIconSize);
        canvas.drawPath(path, buttonIconPaint);//畫豎線
        canvas.restore();
    }
}
複製程式碼

新增attrs屬性

<declare-styleable name="HorizontalExpandMenu">
	//省略部分程式碼...
	<attr name="button_style">
		<enum name="right" value="0"/>
		<enum name="left" value="1"/>
	</attr>
	<attr name="button_icon_size" format="dimension"></attr>
	<attr name="button_icon_stroke_width" format="dimension"></attr>
	<attr name="button_icon_color" format="color"></attr>
</declare-styleable>
複製程式碼

佈局檔案

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <com.anlia.expandmenu.widget.HorizontalExpandMenu
            android:id="@+id/expandMenu1"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp">
        </com.anlia.expandmenu.widget.HorizontalExpandMenu>
        <com.anlia.expandmenu.widget.HorizontalExpandMenu
            android:id="@+id/expandMenu2"
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            app:button_style="left">
        </com.anlia.expandmenu.widget.HorizontalExpandMenu>
    </LinearLayout>
</RelativeLayout>
複製程式碼

效果如圖

Android自定義View——從零開始實現可展開收起的水平選單欄


設定按鈕動畫與點選事件

之前我們定義了buttonIconDegrees屬性,下面我們通過Animation的插值器增減buttonIconDegrees的數值讓按鈕符號可以進行變換,同時監聽Touch為按鈕設定點選事件

public class HorizontalExpandMenu extends RelativeLayout {
	//省略部分程式碼...
    private boolean isExpand;//選單是否展開,預設為展開
    private float downX = -1;
    private float downY = -1;
    private int expandAnimTime;//展開收起選單的動畫時間

    private void init(){
		//省略部分程式碼...
        buttonIconDegrees = 90;//選單初始狀態為展開,所以旋轉角度為90,按鈕符號為 - 號
        expandAnimTime = typedArray.getInteger(R.styleable.HorizontalExpandMenu_expand_time,400);
        isExpand = true;
        anim = new ExpandMenuAnim();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                downX = event.getX();
                downY = event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                switch (buttonStyle){
                    case ButtonStyle.Right:
                        if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
                            expandMenu(expandAnimTime);
                        }
                        break;
                    case ButtonStyle.Left:
                        if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
                            expandMenu(expandAnimTime);
                        }
                        break;
                }
                break;
        }
        return true;
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            if(isExpand){//展開選單
                buttonIconDegrees = 90 * interpolatedTime;
            }else {//收起選單
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            postInvalidate();
        }
    }

    /**
     * 展開收起選單
     * @param time 動畫時間
     */
    private void expandMenu(int time){
        anim.setDuration(time);
        isExpand = isExpand ?false:true;
        this.startAnimation(anim);
    }
}
複製程式碼

效果如圖

Android自定義View——從零開始實現可展開收起的水平選單欄


設定選單展開收起動畫

ViewGroup的大小和位置需要用到layout()方法進行設定,和按鈕動畫一樣,我們使用動畫插值器動態改變選單的長度

public class HorizontalExpandMenu extends RelativeLayout {
	//省略部分程式碼...
    private float backPathWidth;//繪製子View區域寬度
    private float maxBackPathWidth;//繪製子View區域最大寬度
    private int menuLeft;//menu區域left值
    private int menuRight;//menu區域right值

    private boolean isFirstLayout;//是否第一次測量位置,主要用於初始化menuLeft和menuRight的值

    private void init(){
		//省略部分程式碼...
        isFirstLayout = true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		//省略部分程式碼...
        maxBackPathWidth = viewWidth- buttonRadius *2;
        backPathWidth = maxBackPathWidth;
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        //如果子View數量為0時,onLayout後getLeft()和getRight()才能獲取相應數值,menuLeft和menuRight儲存menu初始的left和right值
        if(isFirstLayout){
            menuLeft = getLeft();
            menuRight = getRight();
            isFirstLayout = false;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;//當menu的寬度改變時,重新給viewWidth賦值
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
		//省略部分程式碼...
        switch (event.getAction()){
            case MotionEvent.ACTION_UP:
                if(backPathWidth==maxBackPathWidth || backPathWidth==0){//動畫結束時按鈕才生效
                    switch (buttonStyle){
                        case ButtonStyle.Right:
                            if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=rightButtonLeft&&x<=rightButtonRight){
                                expandMenu(expandAnimTime);
                            }
                            break;
                        case ButtonStyle.Left:
                            if(x==downX&&y==downY&&y>=buttonTop&&y<=buttonBottom&&x>=leftButtonLeft&&x<=leftButtonRight){
                                expandMenu(expandAnimTime);
                            }
                            break;
                    }
                }
                break;
        }
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            float left = menuRight - buttonRadius *2;//按鈕在右邊,選單收起時按鈕區域left值
            float right = menuLeft + buttonRadius *2;//按鈕在左邊,選單收起時按鈕區域right值

            if(isExpand){//開啟選單
                backPathWidth = maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 * interpolatedTime;
            }else {//關閉選單
                backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            if(buttonStyle == ButtonStyle.Right){
                layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//會呼叫onLayout重新測量子View位置
            }else {
                layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
            }
            postInvalidate();
        }
    }
}
複製程式碼

效果如圖

Android自定義View——從零開始實現可展開收起的水平選單欄


測量選單欄子View的位置

為了選單欄的顯示效果,我們限制其直接子View的數量為一個。在子View數量不為0的情況下,我們需要動態顯示和隱藏子View,且在onLayout()方法中測量子View的位置,修改HorizontalExpandMenu

public class HorizontalExpandMenu extends RelativeLayout {
	//省略部分程式碼...
    private boolean isAnimEnd;//動畫是否結束
    private View childView;

    private void init(){
		//省略部分程式碼...
        isAnimEnd = false;
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {}

            @Override
            public void onAnimationEnd(Animation animation) {
                isAnimEnd = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {}
        });
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        //如果子View數量為0時,onLayout後getLeft()和getRight()才能獲取相應數值,menuLeft和menuRight儲存menu初始的left和right值
        if(isFirstLayout){
            menuLeft = getLeft();
            menuRight = getRight();
            isFirstLayout = false;
        }
        if(getChildCount()>0){
            childView = getChildAt(0);
            if(isExpand){
                if(buttonStyle == Right){
                    childView.layout(leftButtonCenter.x,(int) buttonTop,(int) rightButtonLeft,(int) buttonBottom);
                }else {
                    childView.layout((int)(leftButtonRight),(int) buttonTop,rightButtonCenter.x,(int) buttonBottom);
                }

                //限制子View在選單內,LayoutParam型別和當前ViewGroup一致
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(viewWidth,viewHeight);
                layoutParams.setMargins(0,0,buttonRadius *3,0);
                childView.setLayoutParams(layoutParams);
            }else {
                childView.setVisibility(GONE);
            }
        }
        if(getChildCount()>1){//限制直接子View的數量
            throw new IllegalStateException("HorizontalExpandMenu can host only one direct child");
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;//當menu的寬度改變時,重新給viewWidth賦值
        if(isAnimEnd){//防止出現動畫結束後選單欄位置大小測量錯誤的bug
            if(buttonStyle == Right){
                if(!isExpand){
                    layout((int)(menuRight - buttonRadius *2-backPathWidth),getTop(), menuRight,getBottom());
                }
            }else {
                if(!isExpand){
                    layout(menuLeft,getTop(),(int)(menuLeft + buttonRadius *2+backPathWidth),getBottom());
                }
            }
        }
    }

    private class ExpandMenuAnim extends Animation {
        public ExpandMenuAnim() {}

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            float left = menuRight - buttonRadius *2;//按鈕在右邊,選單收起時按鈕區域left值
            float right = menuLeft + buttonRadius *2;//按鈕在左邊,選單收起時按鈕區域right值
            if(childView!=null) {
                childView.setVisibility(GONE);
            }
            if(isExpand){//開啟選單
                backPathWidth = maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 * interpolatedTime;

                if(backPathWidth==maxBackPathWidth){
                    if(childView!=null) {
                        childView.setVisibility(VISIBLE);
                    }
                }
            }else {//關閉選單
                backPathWidth = maxBackPathWidth - maxBackPathWidth * interpolatedTime;
                buttonIconDegrees = 90 - 90 * interpolatedTime;
            }
            if(buttonStyle == Right){
                layout((int)(left-backPathWidth),getTop(), menuRight,getBottom());//會呼叫onLayout重新測量子View位置
            }else {
                layout(menuLeft,getTop(),(int)(right+backPathWidth),getBottom());
            }
            postInvalidate();
        }
    }

    /**
     * 展開收起選單
     * @param time 動畫時間
     */
    private void expandMenu(int time){
        anim.setDuration(time);
        isExpand = isExpand ?false:true;
        this.startAnimation(anim);
        isAnimEnd = false;
    }
}
複製程式碼

佈局程式碼

<LinearLayout
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical">
	<com.anlia.expandmenu.widget.HorizontalExpandMenu
		android:id="@+id/expandMenu1"
		android:layout_width="match_parent"
		android:layout_height="40dp"
		android:layout_marginTop="20dp"
		android:layout_marginLeft="15dp"
		android:layout_marginRight="15dp">
		<LinearLayout
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:orientation="horizontal"
			android:gravity="center_vertical"
			android:clickable="true">
			<TextView
				android:layout_width="0dp"
				android:layout_height="match_parent"
				android:layout_weight="1"
				android:gravity="center"
				android:text="item1"/>
			<TextView
				android:layout_width="0dp"
				android:layout_height="match_parent"
				android:layout_weight="1"
				android:gravity="center"
				android:text="item2"/>
			<TextView
				android:layout_width="0dp"
				android:layout_height="match_parent"
				android:layout_weight="1"
				android:gravity="center"
				android:text="item3"/>
			<TextView
				android:layout_width="0dp"
				android:layout_height="match_parent"
				android:layout_weight="1"
				android:gravity="center"
				android:text="item4"/>
		</LinearLayout>
	</com.anlia.expandmenu.widget.HorizontalExpandMenu>
	<com.anlia.expandmenu.widget.HorizontalExpandMenu
		android:id="@+id/expandMenu2"
		android:layout_width="match_parent"
		android:layout_height="40dp"
		android:layout_marginTop="15dp"
		android:layout_marginLeft="15dp"
		android:layout_marginRight="15dp"
		app:button_style="left">
		<HorizontalScrollView
			android:layout_width="match_parent"
			android:layout_height="match_parent"
			android:fillViewport="true"
			android:scrollbars="none">
			<LinearLayout
				android:layout_width="wrap_content"
				android:layout_height="match_parent"
				android:orientation="horizontal"
				android:gravity="center_vertical"
				android:clickable="true">
				<TextView
					android:layout_width="100dp"
					android:layout_height="match_parent"
					android:gravity="center"
					android:background="@color/blue"
					android:text="item1"/>
				<TextView
					android:layout_width="50dp"
					android:layout_height="match_parent"
					android:gravity="center"
					android:background="@color/yellow"
					android:text="item2"/>
				<TextView
					android:layout_width="100dp"
					android:layout_height="match_parent"
					android:gravity="center"
					android:background="@color/green"
					android:text="item3"/>
				<TextView
					android:layout_width="150dp"
					android:layout_height="match_parent"
					android:gravity="center"
					android:background="@color/red"
					android:text="item4"/>
			</LinearLayout>
		</HorizontalScrollView>
	</com.anlia.expandmenu.widget.HorizontalExpandMenu>
</LinearLayout>
複製程式碼

效果如圖

Android自定義View——從零開始實現可展開收起的水平選單欄

至此本篇教程到此結束,如果大家看了感覺還不錯麻煩點個贊,你們的支援是我最大的動力~


相關文章