如图效果
思路:如图可以将图片中布局分成三个部分,1标题栏透明背景,2上半部分布局,3下半部分布局,当我们向上拉动的时候,1布局实现渐变,从透明变到白色,2布局背景色渐变到白色,23布局随滚动条上拉,并且慢慢改变2布局paddingtop的属性,其中1布局漂浮在整个scrollview布局之上,23布局放在scrollview布局里边。
方法:最主要的问题是怎么样知道上拉的距离并且精确地设定每个布局相应的变化,用到的最重要的一个方法是scrollview的一个监听方法。ScrollViewListener的onScrollChanged方法,但是这个方法在默认的ScrollView控件中是不暴露出来给我们用的,所以需要重写控件。
/**
* 自定义csrollview用来实现标题岁滚动变化透明度
* Created by song on 2016/10/17.
*/
public class MyScrollView extends ScrollView {
public interface ScrollViewListener{
void onScrollChanged(int l, int t, int oldl, int oldt);
}
private ScrollViewListener scrollViewListener=null;
public MyScrollView(Context context) {
super(context);
}
public MyScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (scrollViewListener !=null){
scrollViewListener.onScrollChanged( l, t, oldl, oldt);
}
}
}
在显示的activity中调取
ViewTreeObserver observer = layout2.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
height = layout2.getHeight() - doctorInfoshowTitle.getHeight();
doctorInfoshowSc.setScrollViewListener(new MyScrollView.ScrollViewListener() {
@Override
public void onScrollChanged(int l, int t, int oldl, int oldt) {
if (t <= 0) {
layout2.setBackgroundColor(Color.argb(255, 12, 183, 197));
CenterText.setTextColor(Color.argb(0, 255, 255, 255));
showTitle.setBackgroundColor(Color.argb(0, 255, 255, 255));
layout2.setPadding(0, pt, 0, 0);
} else if (t > 0 && t < height) {
//计算滑动时缩放比率
float scale = (float) t / height;
float apche = ((1 - scale) * 255);
float apche2 = (scale * 255);
layout2.setBackgroundColor(Color.argb((int) apche, 12, 183, 197));
//字体更改
CenterText.setTextColor(Color.argb((int) apche2, 102, 102, 102));
showTitle.setBackgroundColor(Color.argb((int) apche2, 255, 255, 255));
layout2.setPadding(0, (int) (pt + 250 * scale), 0, 0);
} else {
layout2.setBackgroundColor(Color.argb(0, 12, 183, 197));
CenterText.setTextColor(Color.rgb(102, 102, 102));
showTitle.setBackgroundColor(Color.argb(255, 255, 255, 255));
layout2.setPadding(0, pt+250, 0, 0);
}
//如果滑动到ct位置则不显示,控制标题栏上文字的现实和隐藏
if (t >= cheight) {
CenterText.setVisibility(View.VISIBLE);
showLeftBack.setImageDrawable(getResources().getDrawable(R.drawable.back3));
} else {
showCenterText.setVisibility(View.INVISIBLE);
showLeftBack.setImageDrawable(getResources().getDrawable(R.drawable.back));
}
if (t > 400) {//400时我自己设置的一个对应的高度
showLineBottom.setVisibility(View.VISIBLE);
} else {
showLineBottom.setVisibility(View.GONE);
}
}
});
}
});
方法中可以根据上拉的位移来计算渐变和padding值,实现效果