Ejemplo n.º 1
0
  /**
   * 监听触摸事件
   *
   * @param event
   * @return
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    flag = false; // 将事件置为false
    switch (event.getAction()) {
        // 当手指放下的时候
      case MotionEvent.ACTION_DOWN:
        {
          float currentX = event.getX();
          x = currentX - switch_button.getWidth() / 2;
          break;
        }
        // 当手指移动的时候
      case MotionEvent.ACTION_MOVE:
        {
          float currentX = event.getX();
          x = currentX - switch_button.getWidth() / 2;

          break;
        }
        // 当手指抬起的时候
      case MotionEvent.ACTION_UP:
        {
          // 判断当前滑块的位置
          if (x + switch_button.getWidth() / 2 > slide_background.getWidth() / 2) {
            // 滑块已经过半了
            x = slide_background.getWidth() - switch_button.getWidth();
            // 判断是否弹窗
            if (!state.equals(ToggleState.Open)) {
              Toast.makeText(getContext(), "已经开启", Toast.LENGTH_SHORT).show();
              state = ToggleState.Open;
            }
          } else {
            // 滑块没有过半
            x = 0;
            // 判断是否弹窗
            if (!state.equals(ToggleState.Close)) {
              Toast.makeText(getContext(), "已经关闭", Toast.LENGTH_SHORT).show();
              state = ToggleState.Close;
            }
          }
          break;
        }
    }
    // 将状态告知外界
    listener.onStateChange(state);
    // 通知重绘
    invalidate();

    return true; // 设置为true表示自己处理触摸事件
  }
Ejemplo n.º 2
0
 /**
  * 进行绘制
  *
  * @param canvas
  */
 @Override
 protected void onDraw(Canvas canvas) {
   super.onDraw(canvas);
   Paint paint = new Paint();
   /** 绘制背景 参数一:绘制的图片 参数二:left,左上的坐标 参数三:top,顶部的坐标 注意这里的坐标指的是View,不是指的RelativeLayout */
   canvas.drawBitmap(slide_background, 0, 0, paint);
   // 用于初始化
   if (flag) {
     if (state.equals(ToggleState.Open)) {
       x = slide_background.getWidth() - switch_button.getWidth();
     } else {
       x = 0;
     }
   }
   // 限制滑块的位置
   if (x < 0) {
     x = 0;
   } else if (x > slide_background.getWidth() - switch_button.getWidth()) {
     x = slide_background.getWidth() - switch_button.getWidth();
   }
   /** 绘制滑块 */
   canvas.drawBitmap(switch_button, x, 0, paint);
 }