参考文章
自定义的RecyclerView
package com.example.test0908;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* @author writing
* @time 2020/9/1110:24
* @note
*/
public class MyRecyclerView extends RecyclerView {
private LinearLayoutManager linearLayoutManager;
private View firstView;
private View lastView;
public MyRecyclerView(@NonNull Context context) {
super(context);
init();
}
public MyRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MyRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
}
@Override
public void setLayoutManager(@Nullable LayoutManager layout) {
super.setLayoutManager(layout);
linearLayoutManager = (LinearLayoutManager) layout;
}
@Override
public void onScrolled(int dx, int dy) {
super.onScrolled(dx, dy);
Log.i("zhang_xin1", "onScrolled:dx:" + dx + ",dy:" + dy);
Log.i("zhang_xin2", "canScrollVertically" + canScrollVertically(-1));
//表示能否向下滚动
if (canScrollVertically(-1)) {
if(lastView!=null){
lastView.setAlpha(1f);
}
int first = linearLayoutManager.findFirstVisibleItemPosition();
firstView = linearLayoutManager.findViewByPosition(first);
if (firstView.getTop() < 0) {
Log.i("zhang_xin2", "Math.abs(getTop())/firstView.getHeight():" + (float)Math.abs(firstView.getTop())+" "+firstView.getHeight());
firstView.setAlpha(1-(float) Math.abs(firstView.getTop())/firstView.getHeight());
}
lastView = firstView;
}else{
firstView = linearLayoutManager.findViewByPosition(0);
firstView.setAlpha(1f);
}
//表示能否向上滚动
// if(canScrollVertically(1)){
// int first = linearLayoutManager.findFirstVisibleItemPosition();
// View firstView = linearLayoutManager.findViewByPosition(first+1);
// Log.i("zhang_xin2", "firstView.getTop():" + firstView.getTop());
// if (firstView.getTop()>0) {
// firstView.setAlpha(1f);
// }
// }
}
@Override
public void onScreenStateChanged(int screenState) {
super.onScreenStateChanged(screenState);
}
@Override
public boolean canScrollHorizontally(int direction) {
return super.canScrollHorizontally(direction);
}
@Override
public boolean canScrollVertically(int direction) {
return super.canScrollVertically(direction);
}
}