全程自定義view繪製的一個開關器
阿新 • • 發佈:2018-12-10
我們在生活中總會用到一些東西,有一個東西來管理的 那就是開關
下面我們就寫一個自定義view繪製的開關了
下面就直接上程式碼了
public class KaiGuan extends View { boolean flag=true; private final Paint paint; public interface KaiGuanJieKou{ void kai(); void guan(); } KaiGuanJieKou kaiGuanJieKou; public void setKaiGuanJieKou(KaiGuanJieKou kaiGuanJieKou) { this.kaiGuanJieKou = kaiGuanJieKou; } public KaiGuan(Context context, @Nullable AttributeSet attrs) { super(context, attrs); paint = new Paint(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(75,40); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int measuredWidth = getMeasuredWidth();//當前控制元件的寬度 int measuredHeight = getMeasuredHeight();//當前控制元件的高度 paint.setStrokeWidth(1); paint.setColor(getResources().getColor(R.color.lvse)); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true); //預設背景開關 左邊綠色,右邊白圓 /** * 將開關分為三個部分,兩邊半圓,中間正方形 */ int ziwidth = measuredWidth / 3; int ziheight = measuredHeight / 2; if(flag){ paint.setColor(getResources().getColor(R.color.qianhuise)); //最左邊綠色半圓 引數1,確認半圓的大小,,引數2,繪製的起始角度,,引數3,是繪製的總和角度,,引數4,是否包含圓心,引數5,畫筆 //引數2和引數3,一定要遵循android的y軸的特殊性,以及引數3的正/逆時針的旋轉 canvas.drawArc(new RectF(0,0,ziwidth*2,measuredHeight),90,180,true,paint); //繪製中心的方塊 canvas.drawRect(ziwidth,0,ziwidth*2,measuredHeight,paint); //繪製最右邊的半圓 canvas.drawArc(new RectF(ziwidth,0,measuredWidth,measuredHeight),90,-180,true,paint); //移動器 paint.setStrokeWidth(1); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true); //左邊魚眼 引數1,圓心的x座標,引數2,圓心的y軸座標,,引數3,圓的半徑 canvas.drawCircle(ziwidth,ziheight,ziheight-2,paint); }else{ //最左邊綠色半圓 引數1,確認半圓的大小,,引數2,繪製的起始角度,,引數3,是繪製的總和角度,,引數4,是否包含圓心,引數5,畫筆 //引數2和引數3,一定要遵循android的y軸的特殊性,以及引數3的正/逆時針的旋轉 canvas.drawArc(new RectF(0,0,ziwidth*2,measuredHeight),90,180,true,paint); //繪製中心的方塊 canvas.drawRect(ziwidth,0,ziwidth*2,measuredHeight,paint); //繪製最右邊的半圓 canvas.drawArc(new RectF(ziwidth,0,measuredWidth,measuredHeight),90,-180,true,paint); //移動器 預設在右邊 paint.setStrokeWidth(1); paint.setColor(Color.WHITE); paint.setStyle(Paint.Style.FILL_AND_STROKE); paint.setAntiAlias(true); //右邊魚眼 引數1,圓心的x座標,引數2,圓心的y軸座標,,引數3,圓的半徑 canvas.drawCircle(ziwidth*2,ziheight,ziheight-2,paint); } } @Override public boolean onTouchEvent(MotionEvent event) { if(event.getAction()==MotionEvent.ACTION_DOWN){ int x = (int)event.getX(); if(x <getMeasuredWidth()/2){ flag=true; kaiGuanJieKou.guan(); }else{ flag=false; kaiGuanJieKou.kai(); } } postInvalidate(); return true; } }
然後再你用的哪個位置,把這個開關的空間給加進去,給一個id
比如:
然後我們這時候直接給一個id然後調取我們寫的一個自定義介面就可以用了。。