Android開發(fā)仿IOS滑動開關(guān)實現(xiàn)代碼
Android開發(fā)仿IOS滑動開關(guān)實現(xiàn)代碼
Android與iOS相比,ios好多控件都是自帶的,而android需要使用自定義來實現(xiàn)。今天說的是ios的滑動開關(guān),我層看到好多博客都是通過自定義ToggleButton實現(xiàn)的。這里我通過自定義view來實現(xiàn)他的效果。
首先在onsizechange里把2個半圓和一個矩形繪制出來。
width = w; height = h; left = top = 0; right = width; bottom = height * 0.8f; cx = (right + left) / 2; cy = (bottom + top) / 2; RectF rectF = new RectF(left, top, bottom, bottom); path.arcTo(rectF, 90, 180); rectF.left = right - bottom; rectF.right = right; path.arcTo(rectF, 270, 180); path.close(); circle_left = 0; circle_right = bottom; circle_width = circle_right - circle_left; float circle_height = (bottom - top) / 2; radius = circle_height * 0.9f; borderwidth = (int) (2 * (circle_height - radius)); circle_cx = width - circle_height;
剩下的就是ondraw方法來繪制顏色,以及切換的效果。
protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setStyle(Style.FILL); paint.setAntiAlias(true); canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG)); if (isChoose) { paint.setColor(onColor); } else { paint.setColor(offColor); } canvas.drawPath(path, paint); isAnimation = isAnimation - 0.1f > 0 ? isAnimation - 0.1f : 0; //縮放大小參數(shù)隨isAnimation變化而變化 final float scale = 0.98f * (isChoose ? isAnimation : 1 - isAnimation); //保存canvas狀態(tài) canvas.save(); canvas.scale(scale, scale, circle_cx, cy); paint.setColor(offColor); canvas.drawPath(path, paint); canvas.restore(); paint.reset(); float bTranslateX = width - circle_width; final float translate = bTranslateX * (isChoose ? 1 - isAnimation : isAnimation); canvas.translate(translate, 0); if (isAnimation > 0) { invalidate(); } canvas.save(); paint.setStyle(Style.FILL); paint.setColor(offColor); canvas.drawCircle(circle_width / 2, circle_width / 2, radius, paint); // 按鈕白底 paint.setStyle(Style.STROKE); paint.setColor(borderColor); paint.setStrokeWidth(borderwidth); canvas.drawCircle(circle_width / 2, circle_width / 2, radius, paint); // 按鈕灰邊 canvas.restore(); }
最后我們在ontouch里面去改變他的狀態(tài):
public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: return true; case MotionEvent.ACTION_CANCEL: return true; case MotionEvent.ACTION_UP: isAnimation = 1; isChoose = !isChoose; listener.onStateChanged(isChoose); invalidate(); break; } return super.onTouchEvent(event); }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android開發(fā)之使用ViewPager實現(xiàn)圖片左右滑動切換效果
這篇文章主要介紹了Android開發(fā)之使用ViewPager實現(xiàn)圖片左右滑動切換效果的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08詳談Matrix中preTranslate()和postTranslate()的理解
這篇文章主要為大家詳細介紹了Matrix中preTranslate()和postTranslate()的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11Android編程中聊天頁面背景圖片、標(biāo)題欄由于鍵盤引起問題的解決方法
這篇文章主要介紹了Android編程中聊天頁面背景圖片、標(biāo)題欄由于鍵盤引起問題的解決方法,針對鍵盤彈出時標(biāo)題欄及背景圖片異常的相關(guān)解決方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-10-10Android利用ContentProvider獲取聯(lián)系人信息
這篇文章主要為大家詳細介紹了Android利用ContentProvider獲取聯(lián)系人信息,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11