SoFunction
Updated on 2025-04-09

Android custom implementation of slideable buttons

This article shares the specific code for Android custom implementation of slideable buttons for your reference. The specific content is as follows

Implementation logic

1. Create a class inherits the view class and implement the onMeasure() onDraw() method inside

2. In onMeasure(), setMeasuredDimension(viewWidth, viewheight) needs to be called to draw the button's position area

3. The background and slider resources of the button need to be loaded and converted into a bitmap object

4. Get the width and height of the background image as the width and height of the custom control

5. Get the width of the slider to adjust the button's on and off

6. Draw the background image and slider in the onDraw() method and display it on the page

7. Create a touch event to listen to the button's location

8. Create a drawSlide method to limit the running interval of the slider, prevent the slider from marking out the specified area, and limit the button to only have two results, on and off

9. Obtain the result of the switch according to the drawSlide method and set the state of the switch

10. Set the position of the slider in the switch according to the status of the switch

11. Set up a callback interface to monitor whether the state of the button has changed

Layout file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
xmlns:tools="/tools"
android:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".a3_.MainActivity">

<.a3_.MyToggleButton
 android:
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

<.a3_.MyToggleButton
 android:
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
</LinearLayout>

Core code

package .a3_;

import .;
import ;
import ;

public class MainActivity extends AppCompatActivity {

private MyToggleButton toggleButton;
private MyToggleButton toggleButton2;

@Override
protected void onCreate(Bundle savedInstanceState) {
 (savedInstanceState);
 setContentView(.activity_main);

 //Initialize the control toggleButton = (MyToggleButton) findViewById();
 //Set the status of the button (true);
 //Create a listener MyListener myListener = new MyListener();
 //Set up the monitoring (myListener);

 //Initialize the control toggleButton2 = (MyToggleButton) findViewById(.myToggle2);
 //Set the status of the button (true);
 //Create a listener MyListener myListener2 = new MyListener();
 //Set up the monitoring (myListener2);

}

//Create a listenerclass MyListener implements  {

 @Override
 public void onToggleStateChange(MyToggleButton button, boolean isToggleOn) {

  //Determine which button triggers the monitoring  switch (()) {
   case :
    (, isToggleOn ? "Open 1" : "Close 1", Toast.LENGTH_SHORT).show();
    break;
   case .myToggle2:
    (, isToggleOn ? "Open 2" : "Close 2", Toast.LENGTH_SHORT).show();
  }

 }
}
}

Custom control code

package .a3_;

import ;
import ;
import ;
import ;
import ;
import ;
import ;

/**
 * Created by Administrator on 2017.05.27.0027.
 */

public class MyToggleButton extends View {

private Bitmap bgBitmap;
private Bitmap slidebg;
private final int viewWidth;
private final int viewheight;
private float slidebgleft;
private final int slideWidth;
private final int slideMaxLeft;
//Set a member variable to determine the state of the switchprivate boolean toggleStste = false;
private boolean canChangeToggleState = false;

private onToggleStateChangedListener monToggleStateChangedListener = null;

//Create a monitor with the state of the switch changed, triggered when the state changes, otherwise it will not triggerpublic void setOnToggleStateChangedListener(onToggleStateChangedListener monToggleStateChangedListener) {
  = monToggleStateChangedListener;
}


public MyToggleButton(Context context, AttributeSet attrs) {
 super(context, attrs);
 //Set the background and slider resources of the button setBackgroundAndSlideResource(.toogle_background, .toogle_slidebg);
 //Get the height and width of the background viewWidth = ();
 viewheight = ();
 //The width and height of the background are the width and height of this custom button //Get the width of the slider slideWidth = ();
 //Calculate the maximum value on the right side of the slider slideMaxLeft = viewWidth - slideWidth;
}

//Define a method to show whether the button is on or offpublic void setToggleStste(boolean toggleStste) {
  = toggleStste;
 if (toggleStste) {
  slidebgleft = slideMaxLeft;
 } else {
  slidebgleft = 0;
 }
 //Repaint invalidate();
}

//Set the background and slider resources of the buttonprivate void setBackgroundAndSlideResource(int toogle_background, int toogle_slidebg) {
 bgBitmap = (getResources(), toogle_background);
 slidebg = (getResources(), toogle_slidebg);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//  (widthMeasureSpec, heightMeasureSpec);
 //Call setMeasuredDimension to draw the button area setMeasuredDimension(viewWidth, viewheight);
}

@Override
protected void onDraw(Canvas canvas) {

 //Rewrite drawBitmap and draw the background and slider of the control into the page (bgBitmap, 0, 0, null);
 drawSlide(canvas);

}

//Control slidebgleft to control the position of the sliderprivate void drawSlide(Canvas canvas) {
 //Limit the running interval of the slider to prevent the slider from moving outside the boundary if (slidebgleft &lt; 0) {
  slidebgleft = 0;
 } else if (slidebgleft &gt; slideMaxLeft) {
  slidebgleft = slideMaxLeft;
 }
 (slidebg, slidebgleft, 0, null);
 if (canChangeToggleState) {
  canChangeToggleState = false;
  //Record the status of the last switch  boolean lastToggleState = toggleStste;
  //Update the status of the switch according to the current slider position  if (slidebgleft == 0) {
   toggleStste = false;
  } else {
   toggleStste = true;
  }

  //If the current state is different from the previous state, the listening event will be triggered  if (lastToggleState != toggleStste &amp;&amp; monToggleStateChangedListener != null) {
   (this, toggleStste);
  }
 }
}

//Set the button's touch event@Override
public boolean onTouchEvent(MotionEvent event) {
 switch (()) {
  case MotionEvent.ACTION_DOWN:
   slidebgleft = () - slideWidth / 2;
   break;
  case MotionEvent.ACTION_MOVE:
   slidebgleft = () - slideWidth / 2;
   break;
  case MotionEvent.ACTION_UP:
   if (() &gt; viewWidth / 2) {
    slidebgleft = slideMaxLeft;
   } else {
    slidebgleft = 0;
   }
   //Only if the monitor can be triggered when the phone leaves the screen   canChangeToggleState = true;
   break;
 }
 //Draw repeatedly invalidate();
 return true;
}

interface onToggleStateChangedListener {
 void onToggleStateChange(MyToggleButton button, boolean isToggleOn);
}
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.