Android Custom Implementation Sliding Button
- 2021-11-01 04:40:17
- OfStack
This article example for everyone to share the Android custom implementation of the slidable button specific code, for your reference, the specific content is as follows
Implementation logic
1. Create a class that inherits the view class and implements the onMeasure () onDraw () method
2. In onMeasure (), you need to call setMeasuredDimension (viewWidth, viewheight) to draw the location area of the button
3. Background and slider resources for buttons need to be loaded and converted to bitmap objects
4. Get the width and height of the background image as the width and height of the custom control
5. Gets the width of the slider, which is used to adjust the button on and off
6. Draw a background image and slider in the onDraw () method and display it on the page
7. Create a touch event that listens for the location of the button
8. Create an drawSlide method to limit the running range of the slider, prevent the slider from drawing out the specified area, and limit the button to only two results, on and off
9. Set the state of the switch according to the result of the switch obtained by drawSlide method
10. Set the position of the slider in the switch according to the state of the switch
11. Set a callback interface to monitor whether the status of the button changes
Layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
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="com.example.a3_.MainActivity">
<com.example.a3_.MyToggleButton
android:id="@+id/myToggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.example.a3_.MyToggleButton
android:id="@+id/myToggle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Core code
package com.example.a3_;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MyToggleButton toggleButton;
private MyToggleButton toggleButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize control
toggleButton = (MyToggleButton) findViewById(R.id.myToggle);
// Set the state of the button
toggleButton.setToggleStste(true);
// Create 1 Monitor
MyListener myListener = new MyListener();
// Set up listening
toggleButton.setOnToggleStateChangedListener(myListener);
// Initialize control
toggleButton2 = (MyToggleButton) findViewById(R.id.myToggle2);
// Set the state of the button
toggleButton2.setToggleStste(true);
// Create 1 Monitor
MyListener myListener2 = new MyListener();
// Set up listening
toggleButton2.setOnToggleStateChangedListener(myListener2);
}
// Create 1 Monitor
class MyListener implements MyToggleButton.onToggleStateChangedListener {
@Override
public void onToggleStateChange(MyToggleButton button, boolean isToggleOn) {
// Determine which button triggered the listening
switch (button.getId()) {
case R.id.myToggle:
Toast.makeText(MainActivity.this, isToggleOn ? " Open 1" : " Guan 1", Toast.LENGTH_SHORT).show();
break;
case R.id.myToggle2:
Toast.makeText(MainActivity.this, isToggleOn ? " Open 2" : " Guan 2", Toast.LENGTH_SHORT).show();
}
}
}
}
Custom control code
package com.example.a3_;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* 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;
// Settings 1 Member variables , Used to determine the state of the switch
private boolean toggleStste = false;
private boolean canChangeToggleState = false;
private onToggleStateChangedListener monToggleStateChangedListener = null;
// Create 1 Monitoring of switch state changes , Triggered when the state changes , Otherwise, it will not trigger
public void setOnToggleStateChangedListener(onToggleStateChangedListener monToggleStateChangedListener) {
this.monToggleStateChangedListener = monToggleStateChangedListener;
}
public MyToggleButton(Context context, AttributeSet attrs) {
super(context, attrs);
// Setting Background and Slider Resources for Buttons
setBackgroundAndSlideResource(R.mipmap.toogle_background, R.mipmap.toogle_slidebg);
// Gets the height and width of the background
viewWidth = bgBitmap.getWidth();
viewheight = bgBitmap.getHeight();
// The width and height of the background is the width and height of this custom button
// Gets the width of the slider
slideWidth = slidebg.getWidth();
// Calculate the maximum value on the right side of the slider
slideMaxLeft = viewWidth - slideWidth;
}
// Definition 1 Methods , Used to show whether the button is on or off
public void setToggleStste(boolean toggleStste) {
this.toggleStste = toggleStste;
if (toggleStste) {
slidebgleft = slideMaxLeft;
} else {
slidebgleft = 0;
}
// Redraw
invalidate();
}
// Setting Background and Slider Resources for Buttons
private void setBackgroundAndSlideResource(int toogle_background, int toogle_slidebg) {
bgBitmap = BitmapFactory.decodeResource(getResources(), toogle_background);
slidebg = BitmapFactory.decodeResource(getResources(), toogle_slidebg);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Call setMeasuredDimension Draws the area of the button
setMeasuredDimension(viewWidth, viewheight);
}
@Override
protected void onDraw(Canvas canvas) {
// Rewrite drawBitmap, Draws the background and slider of the control to the page
canvas.drawBitmap(bgBitmap, 0, 0, null);
drawSlide(canvas);
}
// By controlling slidebgleft, To control the position of the slider
private void drawSlide(Canvas canvas) {
// Limit the running range of the slider , Prevent the slider from moving out of bounds
if (slidebgleft < 0) {
slidebgleft = 0;
} else if (slidebgleft > slideMaxLeft) {
slidebgleft = slideMaxLeft;
}
canvas.drawBitmap(slidebg, slidebgleft, 0, null);
if (canChangeToggleState) {
canChangeToggleState = false;
// On record 1 Status of secondary switch
boolean lastToggleState = toggleStste;
// Update the status of the switch according to the current position of the slider
if (slidebgleft == 0) {
toggleStste = false;
} else {
toggleStste = true;
}
// If the current state is the same as the 1 When the secondary states are different, , The listening event will be triggered
if (lastToggleState != toggleStste && monToggleStateChangedListener != null) {
monToggleStateChangedListener.onToggleStateChange(this, toggleStste);
}
}
}
// Set touch events for buttons
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
slidebgleft = event.getX() - slideWidth / 2;
break;
case MotionEvent.ACTION_MOVE:
slidebgleft = event.getX() - slideWidth / 2;
break;
case MotionEvent.ACTION_UP:
if (event.getX() > viewWidth / 2) {
slidebgleft = slideMaxLeft;
} else {
slidebgleft = 0;
}
// Can monitoring be triggered only when the mobile phone leaves the screen
canChangeToggleState = true;
break;
}
// Draw repeatedly and continuously
invalidate();
return true;
}
interface onToggleStateChangedListener {
void onToggleStateChange(MyToggleButton button, boolean isToggleOn);
}
}