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

當時就非常想通過自己來實現(xiàn)這種仿探探式的效果,然而卻沒什么思路。不過毋庸置疑的是,這種效果的原理肯定和 ListView /RecyclerView 類似,涉及到 Item View 的回收和重用,否則早就因為大量的 Item View 而 OOM 了。
從View入手,RecyclerView 是自帶 Item View 回收和重用功能的,而且,RecyclerView 的布局方式是通過設(shè)置 LayoutManager 來實現(xiàn)的,這樣就充分地把布局和 RecyclerView 搞定了。
繼承 RecyclerView.LayoutManager , 顯示自己管理布局, 比如最多顯示4個view, 并且都是居中顯示.
底部的View還需要進行縮放,平移操作.
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) {
//平移時, 需要用到的參考值
TRANS_Y_GAP = (int) (20 * context.getResources().getDisplayMetrics().density);
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
//必須要實現(xiàn)的方法
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
//在這個方法中進行View的布局操作.此方法會被調(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的緩存機制中拿到一個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進行布局
//我們在布局時,將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,拖動時,topView被拖動,Scale不變,一直為1.
* top-1View 的Scale慢慢變化至1,translation也慢慢恢復(fù)0
* top-2View的Scale慢慢變化至 top-1View的Scale,translation 也慢慢變化只top-1View的translation
* top-3View的Scale要變化,translation巋然不動
*/
//第幾層,舉例子,count =7, 最后一個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));
}
}
}
}
}
谷歌官方提供了一個ItemTouchHelper工具類, 對滑動進行了優(yōu)越封裝
使用方法: new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);就這么簡單,
接下來的操作, 都在回調(diào)callback里面進行.
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() {
//第一個參數(shù)決定可以拖動排序的方向, 這里由于不需要拖動排序,所以傳0
//第二個參數(shù)決定可以支持滑動的方向,這里設(shè)置了上下左右都可以滑動.
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 考慮 探探垂直上下方向滑動,不刪除卡片,這里參照源碼寫死0.5f
return recyclerView.getWidth() * /*getSwipeThreshold(viewHolder)*/ 0.5f;
}
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//由于不支持滑動排序, 所以不需要處理此方法
return false;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//當view需要滑動的時候,會回調(diào)此方法
//但是這個方法只是告訴你View需要滑動, 并不是對View和Adapter進行額外的操作,
//所以, 如果你需要實現(xiàn)滑動刪除, 那么需要在此方法中remove item等.
//我們這里需要對滑動過后的View,進行恢復(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) {
//滑動的比例達到多少之后, 視為滑動
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);
//當你在滑動的過程中, 此方法一直會被回調(diào), 就跟onTouch事件一樣...
//先根據(jù)滑動的dx dy 算出現(xiàn)在動畫的比例系數(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;
}
//對每個ChildView進行縮放 位移
int childCount = recyclerView.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = recyclerView.getChildAt(i);
//第幾層,舉例子,count =7, 最后一個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);
}
}
}
}
//擴展實現(xiàn):點擊按鈕實現(xiàn)左滑效果
public void toLeft(RecyclerView recyclerView) {
if (check(recyclerView)) {
animTo(recyclerView, false);
}
}
//擴展實現(xiàn):點擊按鈕實現(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滑動時回調(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>
布局文件:點擊按鈕
<?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é)一下,在這整個代碼流程中我們主要是運用了自定義 LayoutManager 以及 ItemTouchHelper.Callback
接下來,我們看看效果:

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android 快速實現(xiàn)狀態(tài)欄透明樣式的示例代碼
下面小編就為大家分享一篇Android 快速實現(xiàn)狀態(tài)欄透明樣式的示例代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Android程序開發(fā)之Fragment實現(xiàn)底部導(dǎo)航欄實例代碼
流行的應(yīng)用的導(dǎo)航一般分為兩種,一種是底部導(dǎo)航,一種是側(cè)邊欄。本文給大家介紹Fragment實現(xiàn)底部導(dǎo)航欄,對Fragment實現(xiàn)底部導(dǎo)航欄相關(guān)知識感興趣的朋友一起學(xué)習(xí)吧2016-03-03

