android右划关闭Activity代码

网上找了很多代码,发现便宜又方便的只有这一个了

  1. 新建BaseActivity
/**
* 滑动关闭页面基类,使用时继承此类并使用BlankTheme主题即可
*/
public abstract class BaseSwipeActivity extends BaseActivity {
  private SwipeLayout swipeLayout;
  /**
   * 是否可以滑动关闭页面
   */
  protected boolean swipeEnabled = true;
  /**
   * 是否可以在页面任意位置右滑关闭页面,如果是false则从左边滑才可以关闭。
   */
  protected boolean swipeAnyWhere = false;

  public BaseSwipeActivity() {
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      swipeLayout = new SwipeLayout(this);
  }

  public void setSwipeAnyWhere(boolean swipeAnyWhere) {
      this.swipeAnyWhere = swipeAnyWhere;
  }

  public boolean isSwipeAnyWhere() {
      return swipeAnyWhere;
  }

  public void setSwipeEnabled(boolean swipeEnabled) {
      this.swipeEnabled = swipeEnabled;
  }

  public boolean isSwipeEnabled() {
      return swipeEnabled;
  }

  @Override
  protected void onResume() {
      super.onResume();
  }

  @Override
  protected void onPostCreate(Bundle savedInstanceState) {
      super.onPostCreate(savedInstanceState);
      swipeLayout.replaceLayer(this);
  }

  public static int getScreenWidth(Context context) {
      DisplayMetrics metrics = new DisplayMetrics();
      WindowManager manager = (WindowManager) context.getSystemService(WINDOW_SERVICE);
      manager.getDefaultDisplay().getMetrics(metrics);
      return metrics.widthPixels;
  }

  private boolean swipeFinished = false;

  @Override
  public void finish() {
      if (swipeFinished) {
          super.finish();
          overridePendingTransition(0, 0);
      } else {
          swipeLayout.cancelPotentialAnimation();
          super.finish();
          overridePendingTransition(0, R.anim.slide_out_right);
      }
  }

  class SwipeLayout extends FrameLayout { /*private View backgroundLayer;用来设置滑动时的背景色*/
      private Drawable leftShadow;

      public SwipeLayout(Context context) {
          super(context);
      }

      public SwipeLayout(Context context, AttributeSet attrs) {
          super(context, attrs);
      }

      public SwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
          super(context, attrs, defStyleAttr);
      }

      public void replaceLayer(Activity activity) {
          leftShadow = activity.getResources().getDrawable(R.drawable.left_shadow);
          touchSlop = (int) (touchSlopDP * activity.getResources().getDisplayMetrics().density);
          sideWidth = (int) (sideWidthInDP * activity.getResources().getDisplayMetrics().density);
          mActivity = activity;
          screenWidth = getScreenWidth(activity);
          setClickable(true);
          final ViewGroup root = (ViewGroup) activity.getWindow().getDecorView();
          content = root.getChildAt(0);
          ViewGroup.LayoutParams params = content.getLayoutParams();
          ViewGroup.LayoutParams params2 = new ViewGroup.LayoutParams(-1, -1);
          root.removeView(content);
          this.addView(content, params2);
          root.addView(this, params);
      }

      @Override
      protected boolean drawChild(@NonNull Canvas canvas, @NonNull View child, long drawingTime) {
          boolean result = super.drawChild(canvas, child, drawingTime);
          final int shadowWidth = leftShadow.getIntrinsicWidth();
          int left = (int) (getContentX()) - shadowWidth;
          leftShadow.setBounds(left, child.getTop(), left + shadowWidth, child.getBottom());
          leftShadow.draw(canvas);
          return result;
      }

      boolean canSwipe = false;
      /**
       * 超过了touchslop仍然没有达到没有条件,则忽略以后的动作
       */
      boolean ignoreSwipe = false;
      View content;
      Activity mActivity;
      int sideWidthInDP = 16;
      int sideWidth = 72;
      int screenWidth = 1080;
      VelocityTracker tracker;
      float downX;
      float downY;
      float lastX;
      float currentX;
      float currentY;
      int touchSlopDP = 30;
      int touchSlop = 60;

      @Override
      public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
          if (swipeEnabled && !canSwipe && !ignoreSwipe)
              if (swipeAnyWhere) switch (ev.getAction()) {
                  case MotionEvent.ACTION_DOWN:
                      downX = ev.getX();
                      downY = ev.getY();
                      currentX = downX;
                      currentY = downY;
                      lastX = downX;
                      break;
                  case MotionEvent.ACTION_MOVE:
                      float dx = ev.getX() - downX;
                      float dy = ev.getY() - downY;
                      if (dx * dx + dy * dy > touchSlop * touchSlop)
                          if (dy == 0f || Math.abs(dx / dy) > 1) {
                              downX = ev.getX();
                              downY = ev.getY();
                              currentX = downX;
                              currentY = downY;
                              lastX = downX;
                              canSwipe = true;
                              tracker = VelocityTracker.obtain();
                              return true;
                          } else ignoreSwipe = true;
                      break;
              }
              else if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getX() < sideWidth) {
                  canSwipe = true;
                  tracker = VelocityTracker.obtain();
                  return true;
              }
          if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL)
              ignoreSwipe = false;
          return super.dispatchTouchEvent(ev);
      }

      @Override
      public boolean onInterceptTouchEvent(MotionEvent ev) {
          return canSwipe || super.onInterceptTouchEvent(ev);
      }

      boolean hasIgnoreFirstMove;

      @Override
      public boolean onTouchEvent(@NonNull MotionEvent event) {
          if (canSwipe) {
              tracker.addMovement(event);
              int action = event.getAction();
              switch (action) {
                  case MotionEvent.ACTION_DOWN:
                      downX = event.getX();
                      downY = event.getY();
                      currentX = downX;
                      currentY = downY;
                      lastX = downX;
                      break;
                  case MotionEvent.ACTION_MOVE:
                      currentX = event.getX();
                      currentY = event.getY();
                      float dx = currentX - lastX;
                      if (dx != 0f && !hasIgnoreFirstMove) {
                          hasIgnoreFirstMove = true;
                          dx = dx / dx;
                      }
                      if (getContentX() + dx < 0) setContentX(0);
                      else setContentX(getContentX() + dx);
                      lastX = currentX;
                      break;
                  case MotionEvent.ACTION_UP:
                  case MotionEvent.ACTION_CANCEL:
                      tracker.computeCurrentVelocity(10000);
                      tracker.computeCurrentVelocity(1000, 20000);
                      canSwipe = false;
                      hasIgnoreFirstMove = false;
                      int mv = screenWidth / 200 * 1000;
                      if (Math.abs(tracker.getXVelocity()) > mv)
                          animateFromVelocity(tracker.getXVelocity());
                      else if (getContentX() > screenWidth / 2) animateFinish(false);
                      else animateBack(false);
                      tracker.recycle();
                      break;
                  default:
                      break;
              }
          }
          return super.onTouchEvent(event);
      }

      ObjectAnimator animator;

      public void cancelPotentialAnimation() {
          if (animator != null) {
              animator.removeAllListeners();
              animator.cancel();
          }
      }

      public void setContentX(float x) {
          int ix = (int) x;
          content.setX(ix);
          invalidate();
      }

      public float getContentX() {
          return content.getX();
      }

      /**
       * 弹回,不关闭,因为left是0,所以setX和setTranslationX效果是一样的 @param withVel 使用计算出来的时间
       */
      private void animateBack(boolean withVel) {
          cancelPotentialAnimation();
          animator = ObjectAnimator.ofFloat(this, "contentX", getContentX(), 0);
          int tmpDuration = withVel ? ((int) (duration * getContentX() / screenWidth)) : duration;
          if (tmpDuration < 100) tmpDuration = 100;
          animator.setDuration(tmpDuration);
          animator.setInterpolator(new DecelerateInterpolator());
          animator.start();
      }

      private void animateFinish(boolean withVel) {
          cancelPotentialAnimation();
          animator = ObjectAnimator.ofFloat(this, "contentX", getContentX(), screenWidth);
          int tmpDuration = withVel ? ((int) (duration * (screenWidth - getContentX()) / screenWidth)) : duration;
          if (tmpDuration < 100) tmpDuration = 100;
          animator.setDuration(tmpDuration);
          animator.setInterpolator(new DecelerateInterpolator());
          animator.addListener(new Animator.AnimatorListener() {
              @Override
              public void onAnimationStart(Animator animation) {
              }

              @Override
              public void onAnimationRepeat(Animator animation) {
              }

              @Override
              public void onAnimationEnd(Animator animation) {
                  if (!mActivity.isFinishing()) {
                      swipeFinished = true;
                      mActivity.finish();
                  }
              }

              @Override
              public void onAnimationCancel(Animator animation) {
              }
          });
          animator.start();
      }

      private final int duration = 200;

      private void animateFromVelocity(float v) {
          if (v > 0)
              if (getContentX() < screenWidth / 2 && v * duration / 1000 + getContentX() < screenWidth / 2)
                  animateBack(false);
              else animateFinish(true);
          else if (getContentX() > screenWidth / 2 && v * duration / 1000 + getContentX() > screenWidth / 2)
              animateFinish(false);
          else animateBack(true);
      }
  }
}

2继承该类的activity使用BlankTheme主题

<activity    android:name=".activities.ViewTest"    android:theme="@style/BlankTheme"></activity>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,657评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,662评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,143评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,732评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,837评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,036评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,126评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,868评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,315评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,641评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,773评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,470评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,126评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,859评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,095评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,584评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,676评论 2 351

推荐阅读更多精彩内容