首先自定义ScrollView 代码如下:
public class ListenerScrollView extends NestedScrollView { private ScrollViewListener scrollViewListener = null; public ListenerScrollView(Context context) { super(context); } public ListenerScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public ListenerScrollView(Context context, AttributeSet attrs) { super(context, attrs); } public void setScrollViewListener(ScrollViewListener scrollViewListener) { this.scrollViewListener = scrollViewListener; } @Override protected void onScrollChanged(int x, int y, int oldx, int oldy) { if (scrollViewListener != null) { scrollViewListener.onScrollChanged(this, x, y, oldx, oldy); } super.onScrollChanged(x, y, oldx, oldy); } public interface ScrollViewListener { void onScrollChanged(ListenerScrollView scrollView, int x, int y, int oldx, int oldy); } }
核心代码为监听滑动状态:
@Override public void onScrollChanged(ListenerScrollView scrollView, int x, int y, int oldx, int oldy) { float scale = (float) y / (float) (DensityUtil.dp2px(DetailsActivity.this, 170f) - detailsTitle.getHeight()); int newAlpha = (int) (scale * 255.00f); if (newAlpha <= 0) { newAlpha = 0; } else if (newAlpha > 0 && newAlpha <= 127) { titAlpha = (int) (255 - 255 * scale * 2); detailsTitle.setBackgroundColor(Color.argb(newAlpha, 255, 255, 255)); if (changeBg2) { // ivBack.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_exhibit_back_selector2, null)); // ivTitleRight.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.exhibit_menu_selector, null)); changeBg2 = false; changeBg = true; } } else if (newAlpha > 128 && newAlpha <= 255) { titAlpha = (int) ((scale - 0.5) * 2 * 255.00f); detailsTitle.setBackgroundColor(Color.argb(newAlpha, 255, 255, 255)); if (changeBg) { // ivBack.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.btn_exhibit_back_selector, null)); // ivTitleRight.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.exhibit_menu_selector2, null)); changeBg = false; changeBg2 = true; } } else if (newAlpha > 255) { newAlpha = 255; } detailsTitle.setBackgroundColor(Color.argb(newAlpha, 255, 255, 255)); } }); ScaleAnimation animation = new ScaleAnimation(1.4f, 1.0f, 1.4f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setDuration(200);
工具类:
/** * 将dp类型的尺寸转换成px类型的尺寸 */ public static int dp2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); }