private RecyclerView rv;
private int scrollY;
private float TITLE_MAX_TOP;
private RelativeLayout rlt_my;
private TextView tv_my_title;
private void init() {
rv = root.findViewById(R.id.rv);//列表控件
rlt_my = root.findViewById(R.id.rlt_my);//标题背景色
tv_my_title = root.findViewById(R.id.tv_my_title);//标题字体颜色
//滑动的距离(我的手机1dp=3px)
TITLE_MAX_TOP = MyUtil.dip2px(getActivity(), 47f);
}
private void initData() {
//垂直方向的2列
final StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2,
StaggeredGridLayoutManager.VERTICAL);
//防止Item切换
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
rv.setLayoutManager(layoutManager);
//这是适配器(适配器类就不粘了)
MeListAdapter adapter = new MeListAdapter(getContext());
rv.setAdapter(adapter);
//解决底部滚动到顶部时,顶部item上方偶尔会出现一大片间隔的问题
rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// 累加y值 解决滑动一半y值为0
scrollY = scrollY + dy;
if (scrollY <= 0) { //未滑动时,背景设置透明度为0
rlt_my.setBackgroundColor(Color.argb(0, 255, 255, 255));//背景透明度为0
tv_my_title.setTextColor(Color.argb(0, 51, 51, 51));//标题透明度为0
} else if (scrollY > 0 && scrollY <= TITLE_MAX_TOP) {
//设置透明度,当滑动距离与最大距离相等时,透明度值为255
float s = (float) scrollY / TITLE_MAX_TOP;//滑动距离越小,透明度值越小
float a = (255 * s);
rlt_my.setBackgroundColor(Color.argb((int) a, 255, 255, 255));
tv_my_title.setTextColor(Color.argb((int) a, 51, 51, 51));
} else {//超过渐变区域,透明度都是满的
rlt_my.setBackgroundColor(Color.argb(255, 255, 255, 255));
tv_my_title.setTextColor(Color.argb(255, 51, 51, 51));
}
}
});
}