只有自定义View的代码
package www.bawei.com.newproject;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.renderscript.Allocation;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import java.security.PrivateKey;
/**
* Created by dell on 2017/12/27.
*/
public class SwitchButton extends View {
private Bitmap slide;
private Bitmap backgroud;
private boolean STATE;
private boolean isSTOP;
private int left;
private int move_De;
private onChenageLisinner onChenageLisnner;
public SwitchButton(Context context) {
this(context, null);
}
public SwitchButton(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SwitchButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
backgroud = BitmapFactory.decodeResource(getResources(), R.drawable.breakgroud);
slide = BitmapFactory.decodeResource(getResources(), R.drawable.slid);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(backgroud, 0, 0, null);
if (isSTOP) {
left = move_De - slide.getWidth() / 2;
if (left < 0) {
left = 0;
}
if (left > backgroud.getWidth() / 2) {
left = backgroud.getWidth() / 2;
}
canvas.drawBitmap(slide, left, 0, null);
} else {
if (STATE) {
left = backgroud.getWidth() - slide.getWidth();
} else {
left = 0;
}
canvas.drawBitmap(slide, left, 0, null);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(backgroud.getWidth(), backgroud.getHeight());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
move_De= (int) event.getX();
isSTOP = true;
break;
case MotionEvent.ACTION_MOVE:
move_De = (int) event.getX();
break;
case MotionEvent.ACTION_UP:
move_De = (int) event.getX();
isSTOP = true;
if (move_De < backgroud.getWidth() / 2) {
STATE = true;
} else {
STATE = false;
}
onChenageLisnner.onChenage(STATE);
break;
}
invalidate();
return true;
}
public interface onChenageLisinner {
void onChenage(boolean state);
}
public void setOnChenageLisnner(onChenageLisinner onChenageLisnner) {
this.onChenageLisnner = onChenageLisnner;
}
}