Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Custom switch Button by Android

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "Android how to achieve custom switch buttons", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Android how to achieve custom switch buttons" bar!

I. principle

We put a background picture An in a certain area of the interface, which is "on" on one side and "off" on the other, and places a picture B on this picture, and figure B is about half of figure A. it happens to overwrite the "on" or "off" on figure A. when we click on the picture with our fingers, figure B slides on figure An and covers "on" or "off" accordingly. In this way, the effect of switch button is realized.

2. Implement 1. Customize the View class MyToggle

This class inherits from the View class and implements the OnTouchListener interface. This class implements more functions. Let's break it down and look at it.

1) attribute field

A number of property fields are defined in this class. For more information on the meaning of each property field, please see the code notes.

The specific implementation code is as follows:

/ / background picture of switch on private Bitmap bkgSwitchOn; / / background picture of switch off private Bitmap bkgSwitchOff; / / scrolling picture of switch private Bitmap btnSlip; / / whether the current switch is on private boolean toggleStateOn; / / listening event private OnToggleStateListener toggleStateListener; / / recording the current state of the switch private boolean isToggleStateListenerOn; / / the x coordinate private float proX when the finger presses the screen / / whether the current x coordinate private float currentX; / / is in the sliding state private boolean isSlipping; / / record the state of the last switch private boolean proToggleState\ = true; / / rectangular private Rect rect\ _ on; / / rectangular private Rect rect when the switch is turned off) override the construction method of the View class

What we do in the constructor is to call the init () method we created.

The specific implementation code is as follows:

Public MyToggle (Context context) {super (context); init (context);} public MyToggle (Context context, AttributeSet attrs) {super (context, attrs); init (context);} 3) create init method

The operation implemented in this method is to set the touch event.

The specific implementation code is as follows:

/ / initialization method private void init (Context context) {setOnTouchListener (this);} 4) finger touch event callback method onTouch

This method is the automatic callback method of Android when the finger operates the mobile phone screen, in this method, we monitor the pressing, moving and lifting events of the finger, record the current X coordinates of the finger to judge the moving direction of picture B, so as to realize the movement of picture B on picture A to achieve the effect of button on and off.

The specific implementation code is as follows:

@ Override public boolean onTouch (View v, MotionEvent event) {switch (event.getAction ()) {case MotionEvent.ACTION\ _ DOWN: / / record the x coordinate proX\ = event.getX () when the finger is pressed; currentX\ = proX; / / set the sliding logo to true isSlipping\ = true; break Case MotionEvent.ACTION\ _ MOVE: / / record the current x coordinate currentX\ = event.getX () during finger sliding; break; case MotionEvent.ACTION\ _ UP: / / set the identification of whether to slide to false isSlipping\ = false; / / when the finger is raised (currentX)

< bkgSwitchOn.getWidth() / 2 ){ toggleStateOn \= false; } else { // 处于开启状态 toggleStateOn \= true; } // 如果使用了开关监听器,同时开关的状态发生了改变,这时使用该代码 if(isToggleStateListenerOn && toggleStateOn != proToggleState){ proToggleState \= toggleStateOn; toggleStateListener.onToggleState(toggleStateOn); } break; } invalidate();//重绘 return true; }5)界面重绘方法onDraw 这个方法主要实现的是界面的重绘操作。 只要的思路是: 画背景图A: 当前手指滑动X坐标currentX大于图A宽度的一般时,按钮背景为开启状态; 当前手指滑动X坐标currentX小于图A宽度的一般时,按钮背景为关闭状态; 记录滑块B的X坐标: B滑动时: 当前手指滑动X坐标currentX大于背景图A的宽度,则B坐标为图A宽度减去图B宽度 当前手指滑动X坐标currentX小于背景图A的宽度,则B坐标为当前X坐标currentX减去滑块宽度的一半 B静止: 当按钮处于"开"状态,则B坐标为"开"状态的最左边X坐标 当按钮处于"关"状态,则B坐标为"关"状态的最左边X坐标 具体实现代码如下: @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //用来记录我们滑动块的位置 int left\_slip \= 0; Matrix matrix \= new Matrix(); Paint paint \= new Paint(); if(currentX < bkgSwitchOn.getWidth() / 2){ //在画布上绘制出开关状态为关闭时的 背景图片 canvas.drawBitmap(bkgSwitchOff, matrix, paint); }else{ //在画布上绘制出开关状态为开启时的 背景图片 canvas.drawBitmap(bkgSwitchOn, matrix, paint); } if(isSlipping){//开关是否处于滑动状态 // 滑动块 是否超过了整个滑动按钮的宽度 if(currentX \>

BkgSwitchOn.getWidth () {/ / specify the slider position left\ _ slip\ = bkgSwitchOn.getWidth ()\-btnSlip.getWidth ();} else {/ / set the current slider position left\ _ slip\ = (int) (currentX\-btnSlip.getWidth () / 2) }} whether the else {/ / switch is not sliding if (toggleStateOn) {left\ _ slip\ = rect\ _ on.left;} else {left\ _ slip\ = rect\ _ off.left;}} if (left\ _ slip

< 0){ left\_slip \= 0; } else if( left\_slip \>

BkgSwitchOn.getWidth ()\-btnSlip.getWidth () {left\ _ slip\ = bkgSwitchOn.getWidth ()\-btnSlip.getWidth ();} / draw an image canvas.drawBitmap (btnSlip, left\ _ slip, 0, paint);} 6) calculate the width and height of the switch

Here I calculate the width and height of the switch by overwriting onMeasure.

The specific implementation code is as follows:

/ / calculate the width and height of the switch @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension (bkgSwitchOn.getWidth (), bkgSwitchOn.getHeight ());} 7) set the image resource information

This method is mainly for external calls to provide picture resources to this class.

The specific code implementation is as follows:

/\ *\ * set image resource information\ * @ param bkgSwitch\ _ on\ * @ param bkgSwitch\ _ off\ * @ param btn\ _ Slip\ * / public void setImageRes (int bkgSwitch\ _ on, int bkgSwitch\ _ off, int btn\ _ Slip) {bkgSwitchOn\ = BitmapFactory.decodeResource (getResources (), bkgSwitch\ _ on); bkgSwitchOff\ = BitmapFactory.decodeResource (getResources (), bkgSwitch\ _ off) BtnSlip\ = BitmapFactory.decodeResource (getResources (), btn\ _ Slip); rect\ _ on\ = new Rect (bkgSwitchOn.getWidth ()\-btnSlip.getWidth (), 0off bkgSwitchOn.getWidth (), btnSlip.getHeight ()); rect\ _ off\ = new Rect (0,0, btnSlip.getWidth (), btnSlip.getHeight ();} 8) set the state of the switch button

We record the status identity in this method by passing a state of type boolean.

The specific implementation code is as follows:

/\ *\ * set the status of the switch button\ * @ param state\ * / public void setToggleState (boolean state) {toggleStateOn\ = state;} 9) Custom switch status listener

I define a switch state listener interface OnToggleStateListener in this class, in which there is an onToggleState method to perform the state change listening operation of the button.

The specific code implementation is as follows:

/\ *\ * Custom switch status listener\ * @ author liuyazhuang\ * / interface OnToggleStateListener {abstract void onToggleState (boolean state);} 10) set switch listener

Create a setOnToggleStateListener method, pass an OnToggleStateListener listener object, create an OnToggleStateListener object through the outside world, and pass the OnToggleStateListener object in. We only need to record the OnToggleStateListener object passed by the outside world, and when we call the onToggleState method in the OnToggleStateListener interface, we implement the callback of the onToggleState method in the external OnToggleStateListener implementation class.

The specific code implementation is as follows:

/ / set the switch listener and set the switch listener to true public void setOnToggleStateListener (OnToggleStateListener listener) {toggleStateListener\ = listener; isToggleStateListenerOn\ = true;} 11) the complete code of MyToggle is as follows: package com.lyz.slip.toggle; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect Import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /\ * Custom switch class\ * @ author liuyazhuang\ *\ * / public class MyToggle extends View implements OnTouchListener {/ / background picture on / off private Bitmap bkgSwitchOn; / / background picture on / off private Bitmap bkgSwitchOff; / / scroll picture private Bitmap btnSlip on / off switch / / whether the current switch is on private boolean toggleStateOn; / / listening event of the switch state private OnToggleStateListener toggleStateListener; / / record the current state of the switch private boolean isToggleStateListenerOn; / / the x coordinates private float proX; / / whether the current x coordinates private float currentX; / / is in the sliding state private boolean isSlipping when the finger is pressing down the screen / / record the status of the last switch private boolean proToggleState\ = true; / / rectangular private Rect rect when the switch is on\ _ on; / / rectangular private Rect rect\ _ off; public MyToggle (Context context) {super (context); init (context);} public MyToggle (Context context, AttributeSet attrs) {super (context, attrs); init (context) } / / initialization method private void init (Context context) {setOnTouchListener (this);} @ Override public boolean onTouch (View v, MotionEvent event) {switch (event.getAction ()) {case MotionEvent.ACTION\ _ DOWN: / / record the x coordinate proX\ = event.getX () when the finger is pressed; currentX\ = proX / / set the sliding logo to true isSlipping\ = true; break; case MotionEvent.ACTION\ _ MOVE: / / record the current x coordinates currentX\ = event.getX () during finger sliding; break; case MotionEvent.ACTION\ _ UP: / / set the sliding logo to false isSlipping\ = false when the finger is lifted / / if is closed (currentX

< bkgSwitchOn.getWidth() / 2 ){ toggleStateOn \= false; } else { // 处于开启状态 toggleStateOn \= true; } // 如果使用了开关监听器,同时开关的状态发生了改变,这时使用该代码 if(isToggleStateListenerOn && toggleStateOn != proToggleState){ proToggleState \= toggleStateOn; toggleStateListener.onToggleState(toggleStateOn); } break; } invalidate();//重绘 return true; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //用来记录我们滑动块的位置 int left\_slip \= 0; Matrix matrix \= new Matrix(); Paint paint \= new Paint(); if(currentX < bkgSwitchOn.getWidth() / 2){ //在画布上绘制出开关状态为关闭时的 背景图片 canvas.drawBitmap(bkgSwitchOff, matrix, paint); }else{ //在画布上绘制出开关状态为开启时的 背景图片 canvas.drawBitmap(bkgSwitchOn, matrix, paint); } if(isSlipping){//开关是否处于滑动状态 // 滑动块 是否超过了整个滑动按钮的宽度 if(currentX \>

BkgSwitchOn.getWidth () {/ / specify the slider position left\ _ slip\ = bkgSwitchOn.getWidth ()\-btnSlip.getWidth ();} else {/ / set the current slider position left\ _ slip\ = (int) (currentX\-btnSlip.getWidth () / 2) }} whether the else {/ / switch is not sliding if (toggleStateOn) {left\ _ slip\ = rect\ _ on.left;} else {left\ _ slip\ = rect\ _ off.left;}} if (left\ _ slip

< 0){ left\_slip \= 0; } else if( left\_slip \>

BkgSwitchOn.getWidth ()\-btnSlip.getWidth () {left\ _ slip\ = bkgSwitchOn.getWidth ()\-btnSlip.getWidth ();} / / draw the image canvas.drawBitmap (btnSlip, left\ _ slip, 0, paint);} / / calculate the width and height of the switch @ Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension (bkgSwitchOn.getWidth (), bkgSwitchOn.getHeight ()) } /\ * set image resource information\ * @ param bkgSwitch\ _ on\ * @ param bkgSwitch\ _ off\ * @ param btn\ _ Slip\ * / public void setImageRes (int bkgSwitch\ _ on, int bkgSwitch\ _ off, int btn\ _ Slip) {bkgSwitchOn\ = BitmapFactory.decodeResource (getResources (), bkgSwitch\ _ on); bkgSwitchOff\ = BitmapFactory.decodeResource (getResources (), bkgSwitch\ _ off) BtnSlip\ = BitmapFactory.decodeResource (getResources (), btn\ _ Slip); rect\ _ on\ = new Rect (bkgSwitchOn.getWidth ()\-btnSlip.getWidth (), 0off bkgSwitchOn.getWidth (), btnSlip.getHeight ()); rect\ _ off\ = new Rect (0,0, btnSlip.getWidth (), btnSlip.getHeight ()) } /\ * set the status of the switch button\ * @ param state\ * / public void setToggleState (boolean state) {toggleStateOn\ = state;} /\ * Custom switch status listener\ * @ author liuyazhuang\ * / interface OnToggleStateListener {abstract void onToggleState (boolean state) } / / set the switch listener and set it to true public void setOnToggleStateListener (OnToggleStateListener listener) {toggleStateListener\ = listener; isToggleStateListenerOn\ = true;} 2, MainActivity

The implementation of this class is very simple, and the main function is to load the interface layout, initialize the interface control, and call the methods in the MyToggle class to realize the switch effect of the button.

The specific code implementation is as follows:

Package com.lyz.slip.toggle; import android.app.Activity; import android.os.Bundle; import android.widget.Toast; import com.lyz.slip.toggle.MyToggle.OnToggleStateListener; /\ * Program main entry\ * @ author liuyazhuang\ *\ * / public class MainActivity extends Activity {/ / Custom switch object private MyToggle toggle @ Override public void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity\ _ main); toggle\ = (MyToggle) findViewById (R.id.toggle); / / set the switch to display the picture toggle.setImageRes (R.drawable.bkg\ _ switch, R.drawable.bkg\ _ switch, R.drawable.btn\ _ slip) / / set the default state of the switch true on state toggle.setToggleState (true) / / set the listening toggle.setOnToggleStateListener of the switch (new OnToggleStateListener () {@ Override public void onToggleState (boolean state) {/ / TODO Auto-generated method stub if (state) {Toast.makeText (getApplicationContext (), "switch on", 0) .show () } else {Toast.makeText (getApplicationContext (), "switch off", 0). Show ();});}} 3, layout file activity_main.xml

Here I refer to the self-defined View class MyToggle.

The specific code implementation is as follows:

4 、 AndroidManifest.xml

The specific code is as follows:

Third, the running effect

Thank you for your reading, the above is the content of "Android how to achieve custom switch buttons". After the study of this article, I believe you have a deeper understanding of how to achieve custom switch buttons in Android, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report