第一步
<ToggleButton
android:id="@+id/toggle_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/togglebutton_select" //自定义开关背景
android:textOn="打开" //打开时,显示文本打开
android:textOff="关闭"/> //默认关闭,显示文本关闭
第二步在代码中运行
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ Toast.makeText(ToggleButtonActivity.this,"打开",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(ToggleButtonActivity.this,"关闭",Toast.LENGTH_SHORT).show(); } } }); }
第三步select选择器
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="true" android:drawable="@drawable/icon3"/> <item android:state_checked="false" android:drawable="@drawable/icon4"/> </selector>
自定义switch开关
public class MyButtonView extends View { public Paint paint; public int slidingMax, slidingLength; Bitmap bitmap1; Bitmap bitmap2; public float startx, lastx; boolean ischeck = true; boolean Enable = true; public MyButtonView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); initview(); } private void initview() { paint = new Paint(); paint.setAntiAlias(true); bitmap1 = BitmapFactory.decodeResource(getResources(), R.drawable.switch_background); bitmap2 = BitmapFactory.decodeResource(getResources(), R.drawable.slide_button); slidingMax = bitmap1.getWidth() - bitmap2.getWidth(); this.setOnClickListener(l); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(bitmap1.getWidth(), bitmap1.getHeight()); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(bitmap1, 0, 0, paint); canvas.drawBitmap(bitmap2, slidingLength, 0, paint); } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastx = startx = event.getX(); Enable = true; break; case MotionEvent.ACTION_MOVE: float endx = event.getX(); float distance = endx - startx; slidingLength += distance; if (slidingLength < 0) { slidingLength = 0; } else if (slidingLength > slidingMax) { slidingLength = slidingMax; } invalidate(); startx = event.getX(); if (Math.abs(endx - lastx) > 5) { Enable = false; } break; case MotionEvent.ACTION_UP: if (Enable == false) { if (slidingLength < slidingMax / 2) { ischeck = false; } else { ischeck = true; } flush(); } break; } return true; } private void flush() { if (ischeck == true) { ischeck = false; slidingLength = slidingMax; } else { ischeck = true; slidingLength = 0; } invalidate(); } View.OnClickListener l=new OnClickListener() { @Override public void onClick(View v) { if(Enable==true){ flush(); } } }; }