溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android實(shí)現(xiàn)探探圖片滑動(dòng)效果

發(fā)布時(shí)間:2020-09-16 01:53:55 來源:腳本之家 閱讀:234 作者:qq_26368081 欄目:移動(dòng)開發(fā)

之前一段時(shí)間,在朋友的推薦下,玩了探探這一款軟件,初玩的時(shí)候,就發(fā)現(xiàn),這款軟件與一般的社交軟件如陌陌之類的大相徑庭,讓我耳目一新,特別是探探里關(guān)于圖片滑動(dòng)操作讓人覺得非常新鮮。所以在下通過網(wǎng)上之前的前輩的經(jīng)歷加上自己的理解,也來涉涉水。下面是網(wǎng)上找的探探的原界面

Android實(shí)現(xiàn)探探圖片滑動(dòng)效果

當(dāng)時(shí)就非常想通過自己來實(shí)現(xiàn)這種仿探探式的效果,然而卻沒什么思路。不過毋庸置疑的是,這種效果的原理肯定和 ListView /RecyclerView 類似,涉及到 Item View 的回收和重用,否則早就因?yàn)榇罅康?Item View 而 OOM 了。
從View入手,RecyclerView 是自帶 Item View 回收和重用功能的,而且,RecyclerView 的布局方式是通過設(shè)置 LayoutManager 來實(shí)現(xiàn)的,這樣就充分地把布局和 RecyclerView 搞定了。

繼承 RecyclerView.LayoutManager , 顯示自己管理布局, 比如最多顯示4個(gè)view, 并且都是居中顯示.
底部的View還需要進(jìn)行縮放,平移操作.

public class OverLayCardLayoutManager extends RecyclerView.LayoutManager {
  private static final String TAG = "swipecard";
  public static int MAX_SHOW_COUNT = 4;
  public static float SCALE_GAP = 0.05f;
  public static int TRANS_Y_GAP;

  public OverLayCardLayoutManager(Context context) {
    //平移時(shí), 需要用到的參考值
    TRANS_Y_GAP = (int) (20 * context.getResources().getDisplayMetrics().density);
  }

  @Override
  public RecyclerView.LayoutParams generateDefaultLayoutParams() {
    //必須要實(shí)現(xiàn)的方法
    return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
  }

  @Override
  public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    //在這個(gè)方法中進(jìn)行View的布局操作.此方法會(huì)被調(diào)用多次.
    detachAndScrapAttachedViews(recycler);
    int itemCount = getItemCount();
    if (itemCount < 1) {
      return;
    }
    //top-3View的position
    int bottomPosition;
    //邊界處理
    if (itemCount < MAX_SHOW_COUNT) {
      bottomPosition = 0;
    } else {
      bottomPosition = itemCount - MAX_SHOW_COUNT;
    }

    //從可見的最底層View開始layout,依次層疊上去
    for (int position = bottomPosition; position < itemCount; position++) {
      //1:重recycler的緩存機(jī)制中拿到一個(gè)View
      View view = recycler.getViewForPosition(position);
      //2:和自定義ViewGroup一樣, 需要先addView
      addView(view);
      //3:和自定義ViewGroup一樣, 也需要測量View的大小
      measureChildWithMargins(view, 0, 0);
      int widthSpace = getWidth() - getDecoratedMeasuredWidth(view);
      int heightSpace = getHeight() - getDecoratedMeasuredHeight(view);
      //4:和自定義ViewGroup的onLayout一樣, 需要layout View.對View進(jìn)行布局 
      //我們在布局時(shí),將childView居中處理,這里也可以改為只水平居中
      layoutDecoratedWithMargins(view, widthSpace / 2, heightSpace / 2,
          widthSpace / 2 + getDecoratedMeasuredWidth(view),
          heightSpace / 2 + getDecoratedMeasuredHeight(view));
      /**
       * TopView的Scale 為1,translationY 0
       * 每一級Scale相差0.05f,translationY相差7dp左右
       *
       * 觀察人人影視的UI,拖動(dòng)時(shí),topView被拖動(dòng),Scale不變,一直為1.
       * top-1View 的Scale慢慢變化至1,translation也慢慢恢復(fù)0
       * top-2View的Scale慢慢變化至 top-1View的Scale,translation 也慢慢變化只top-1View的translation
       * top-3View的Scale要變化,translation巋然不動(dòng)
       */

      //第幾層,舉例子,count =7, 最后一個(gè)TopView(6)是第0層,
      int level = itemCount - position - 1;

      //如果不需要縮放平移, 那么下面的代碼可以注釋掉...
      //除了頂層不需要縮小和位移
      if (level > 0 /*&& level < mShowCount - 1*/) {
        //每一層都需要X方向的縮小
        view.setScaleX(1 - SCALE_GAP * level);
        //前N層,依次向下位移和Y方向的縮小
        if (level < MAX_SHOW_COUNT - 1) {
          view.setTranslationY(TRANS_Y_GAP * level);
          view.setScaleY(1 - SCALE_GAP * level);
        } else {//第N層在 向下位移和Y方向的縮小的成都與 N-1層保持一致
          view.setTranslationY(TRANS_Y_GAP * (level - 1));
          view.setScaleY(1 - SCALE_GAP * (level - 1));
        }
      }
    }
  }
}

谷歌官方提供了一個(gè)ItemTouchHelper工具類, 對滑動(dòng)進(jìn)行了優(yōu)越封裝

使用方法: new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);就這么簡單,
接下來的操作, 都在回調(diào)callback里面進(jìn)行.

public class RenRenCallback extends ItemTouchHelper.SimpleCallback {

  private static final String TAG = "RenRen";
  private static final int MAX_ROTATION = 15;
  OnSwipeListener mSwipeListener;
  boolean isSwipeAnim = false;

  public RenRenCallback() {
    //第一個(gè)參數(shù)決定可以拖動(dòng)排序的方向, 這里由于不需要拖動(dòng)排序,所以傳0
    //第二個(gè)參數(shù)決定可以支持滑動(dòng)的方向,這里設(shè)置了上下左右都可以滑動(dòng).
    super(0, ItemTouchHelper.DOWN | ItemTouchHelper.UP | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
  }

  public void setSwipeListener(OnSwipeListener swipeListener) {
    mSwipeListener = swipeListener;
  }

  //水平方向是否可以被回收掉的閾值
  public float getThreshold(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
    //2016 12 26 考慮 探探垂直上下方向滑動(dòng),不刪除卡片,這里參照源碼寫死0.5f
    return recyclerView.getWidth() * /*getSwipeThreshold(viewHolder)*/ 0.5f;
  }

  @Override
  public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    //由于不支持滑動(dòng)排序, 所以不需要處理此方法
    return false;
  }

  @Override
  public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
    //當(dāng)view需要滑動(dòng)的時(shí)候,會(huì)回調(diào)此方法
    //但是這個(gè)方法只是告訴你View需要滑動(dòng), 并不是對View和Adapter進(jìn)行額外的操作,
    //所以, 如果你需要實(shí)現(xiàn)滑動(dòng)刪除, 那么需要在此方法中remove item等.

    //我們這里需要對滑動(dòng)過后的View,進(jìn)行恢復(fù)操作. 
    viewHolder.itemView.setRotation(0);//恢復(fù)最后一次的旋轉(zhuǎn)狀態(tài)
    if (mSwipeListener != null) {
      mSwipeListener.onSwipeTo(viewHolder, 0);
    }
    notifyListener(viewHolder.getAdapterPosition(), direction);
  }

  private void notifyListener(int position, int direction) {
    Log.w(TAG, "onSwiped: " + position + " " + direction);
    if (mSwipeListener != null) {
      mSwipeListener.onSwiped(position, direction);
    }
  }

  @Override
  public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
    //滑動(dòng)的比例達(dá)到多少之后, 視為滑動(dòng)
    return 0.3f;
  }


  @Override
  public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
    super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    //當(dāng)你在滑動(dòng)的過程中, 此方法一直會(huì)被回調(diào), 就跟onTouch事件一樣...
    //先根據(jù)滑動(dòng)的dx dy 算出現(xiàn)在動(dòng)畫的比例系數(shù)fraction
    float swipeValue = (float) Math.sqrt(dX * dX + dY * dY);
    final float threshold = getThreshold(recyclerView, viewHolder);
    float fraction = swipeValue / threshold;
    //邊界修正 最大為1
    if (fraction > 1) {
      fraction = 1;
    } else if (fraction < -1) {
      fraction = -1;
    }
    //對每個(gè)ChildView進(jìn)行縮放 位移
    int childCount = recyclerView.getChildCount();
    for (int i = 0; i < childCount; i++) {
      View child = recyclerView.getChildAt(i);
      //第幾層,舉例子,count =7, 最后一個(gè)TopView(6)是第0層,
      int level = childCount - i - 1;
      if (level > 0) {
        child.setScaleX(1 - SCALE_GAP * level + fraction * SCALE_GAP);

        if (level < MAX_SHOW_COUNT - 1) {
          child.setScaleY(1 - SCALE_GAP * level + fraction * SCALE_GAP);
          child.setTranslationY(TRANS_Y_GAP * level - fraction * TRANS_Y_GAP);
        } else {
          //child.setTranslationY((float) (mTranslationYGap * (level - 1) - fraction * mTranslationYGap));
        }
      } else {
        //最上層
        //rotate
        if (dX < -50) {
          child.setRotation(-fraction * MAX_ROTATION);
        } else if (dX > 50) {
          child.setRotation(fraction * MAX_ROTATION);
        } else {
          child.setRotation(0);
        }

        if (mSwipeListener != null) {
          RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
          final int adapterPosition = params.getViewAdapterPosition();
          mSwipeListener.onSwipeTo(recyclerView.findViewHolderForAdapterPosition(adapterPosition), dX);
        }
      }
    }
  }

  //擴(kuò)展實(shí)現(xiàn):點(diǎn)擊按鈕實(shí)現(xiàn)左滑效果
  public void toLeft(RecyclerView recyclerView) {
    if (check(recyclerView)) {
      animTo(recyclerView, false);
    }
  }

  //擴(kuò)展實(shí)現(xiàn):點(diǎn)擊按鈕實(shí)現(xiàn)右滑效果
  public void toRight(RecyclerView recyclerView) {
    if (check(recyclerView)) {
      animTo(recyclerView, true);
    }
  }

  private void animTo(final RecyclerView recyclerView, boolean right) {
    final int position = recyclerView.getAdapter().getItemCount() - 1;
    final View view = recyclerView.findViewHolderForAdapterPosition(position).itemView;

    TranslateAnimation translateAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0,
        Animation.RELATIVE_TO_SELF, right ? 1f : -1f,
        Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1.3f);
    translateAnimation.setFillAfter(true);
    translateAnimation.setDuration(300);
    translateAnimation.setInterpolator(new DecelerateInterpolator());
    translateAnimation.setAnimationListener(new Animation.AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {

      }

      @Override
      public void onAnimationEnd(Animation animation) {
        isSwipeAnim = false;
        recyclerView.removeView(view);
        notifyListener(position,
            x > view.getMeasuredWidth() / 2
                ?
                ItemTouchHelper.RIGHT : ItemTouchHelper.LEFT);
      }

      @Override
      public void onAnimationRepeat(Animation animation) {

      }
    });
    view.startAnimation(translateAnimation);
  }

  private boolean check(RecyclerView recyclerView) {
    if (isSwipeAnim) {
      return false;
    }
    if (recyclerView == null || recyclerView.getAdapter() == null) {
      return false;
    }
    if (recyclerView.getAdapter().getItemCount() == 0) {
      return false;
    }
    isSwipeAnim = true;
    return true;
  }

  public interface OnSwipeListener {

    /**
     * @param direction {@link ItemTouchHelper#LEFT} / {@link ItemTouchHelper#RIGHT}
     *         {@link ItemTouchHelper#UP} or {@link ItemTouchHelper#DOWN}).
     */
    void onSwiped(int adapterPosition, int direction);

    /**
     * 最上層View滑動(dòng)時(shí)回調(diào).
     *
     * @param viewHolder 最上層的ViewHolder
     * @param offset   距離原始位置的偏移量
     */
    void onSwipeTo(RecyclerView.ViewHolder viewHolder, float offset);
  }

  public static class SimpleSwipeCallback implements OnSwipeListener {

    /**
     * {@inheritDoc}
     */
    @Override
    public void onSwiped(int adapterPosition, int direction) {

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onSwipeTo(RecyclerView.ViewHolder viewHolder, float offset) {

    }
  }
}

布局文件:卡片內(nèi)容

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal|bottom"
  android:layout_marginBottom="20dp"
  android:orientation="horizontal">

  <ImageView
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:background="@drawable/home_buttons_dislike"
    android:onClick="left" />

  <ImageView
    android:id="@+id/info"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"

    android:background="@drawable/home_buttons_info" />

  <ImageView
    android:id="@+id/right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/home_buttons_like"
    />

</LinearLayout>

布局文件:點(diǎn)擊按鈕

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal|bottom"
  android:layout_marginBottom="20dp"
  android:orientation="horizontal">

  <ImageView
    android:id="@+id/left"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"
    android:background="@drawable/home_buttons_dislike"
    android:onClick="left" />

  <ImageView
    android:id="@+id/info"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="10dp"

    android:background="@drawable/home_buttons_info" />

  <ImageView
    android:id="@+id/right"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="@drawable/home_buttons_like"
    />

</LinearLayout>

監(jiān)聽函數(shù):

    flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
   //設(shè)置適配器
    flingContainer.setAdapter(adapter);
    flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
      @Override
      public void removeFirstObjectInAdapter() {
        al.remove(0);
        adapter.notifyDataSetChanged();
      }
      @Override
      public void onLeftCardExit(Object dataObject) {
        makeToast(MainActivity.this, "不喜歡");
      }

      @Override
      public void onRightCardExit(Object dataObject) {
        makeToast(MainActivity.this, "喜歡");
      }

      @Override
      public void onAdapterAboutToEmpty(int itemsInAdapter) {
        al.add(new CardMode("循環(huán)測試", 18, list.get(itemsInAdapter % imageUrls.length - 1)));
        adapter.notifyDataSetChanged();
        i++;
      }

      @Override
      public void onScroll(float scrollProgressPercent) {
        View view = flingContainer.getSelectedView();
        view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
        view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
      }
    });

總結(jié)一下,在這整個(gè)代碼流程中我們主要是運(yùn)用了自定義 LayoutManager 以及 ItemTouchHelper.Callback
接下來,我們看看效果:

Android實(shí)現(xiàn)探探圖片滑動(dòng)效果

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI