1. 程式人生 > >recyclerview 實現卡片滑動效果

recyclerview 實現卡片滑動效果

public void attachToRecyclerView(RecyclerView recyclerView,int margin){ if(recyclerView == null){ return; } mRecycler = recyclerView; if(margin <= 0){ mMargin = mDefaultMargin; }else { mMargin = margin; } initView(); final CustomLinearSnapHelper helper = new CustomLinearSnapHelper(); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if(newState == RecyclerView.SCROLL_STATE_IDLE
){ if(mDistances == 0 || mDistances == (mItemCount*mItemwidth)){ helper.mStateIdle = true; }else{ helper.mStateIdle = false; } } } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if(recyclerView.getLayoutManager().getLayoutDirection() == LinearLayoutManager.HORIZONTAL
){ mDistances += dx; getCurrentPosition(); setItemScale(); } } }); helper.attachToRecyclerView(recyclerView); } //這裡獲取item的寬與countitem數 protected void initView( ){ mRecycler.post(new Runnable() { @Override public void run() { mItemCount = mRecycler.getAdapter().getItemCount(); mItemwidth = mRecycler.getWidth() - 2 * mMargin; mRecycler.smoothScrollToPosition(mCurrentPosition); setItemScale(); } }); } //item在滑動時,進行動畫的縮放 public void setItemScale(){ View leftView = null; View rightView = null; if(mCurrentPosition > 0){ leftView = mRecycler.getLayoutManager().findViewByPosition(mCurrentPosition - 1); } View currentView = mRecycler.getLayoutManager().findViewByPosition(mCurrentPosition); if(mCurrentPosition < (mItemCount - 1)){ rightView = mRecycler.getLayoutManager().findViewByPosition(mCurrentPosition +1); } //滑動百分比,左右的都是放大,中間縮小
float percent = Math.abs((mDistances - mCurrentPosition * mItemwidth*1.0f)/mItemwidth); if(leftView != null){ //這裡是縮小原來大小的0.8-1.0 左右0.8,中間1.0 0.8+(percent*0.2) leftView.setScaleY(0.8f+(percent*0.2f)); } if(currentView != null){ currentView.setScaleY(1-0.2f*percent); } if(rightView != null){ rightView.setScaleY(0.8f+(percent*0.2f)); } } protected void getCurrentPosition(){ if(mItemwidth <= 0) return; boolean change = false; if (Math.abs(mDistances - mCurrentPosition * mItemwidth) >= mItemwidth) { change = true; } if (change) { //這裡是從0開始的 mCurrentPosition = mDistances / mItemwidth; } } public static void setItemPosition(int position){ this.mCurrentPosition = position; this.mDistances = position * mItemwidth;