類似這種效果,想必大家都看過,如某寶的商品詳情頁,小米商城首頁等。。。
我們這里是自定義一個ScrollView去監(jiān)聽控件的滑動,然后不斷去改變標題欄的透明度。
/**
*? ? Created by zwr on 2017/3/11.
* ? ? 自定義的ScrollView
*/
```
publicclassChangeAlphaScrollViewextendsScrollView {
privateOnScrollChangedListenermOnScrollChangedListener;
publicChangeAlphaScrollView(Context context) {
? ? ? ? ? super(context);
}
```
publicChangeAlphaScrollView(Context context, AttributeSet attrs) {
? ? ? ? ? super(context, attrs); ? ? ?
}
publicChangeAlphaScrollView(Context context, AttributeSet attrs,intdefStyleAttr) {
? ? ? ? super(context, attrs, defStyleAttr);
}
@Override
protectedvoidonScrollChanged(intl,intt,intoldl,intoldt) {
? ? ? ? ? ? ?super.onScrollChanged(l, t, oldl, oldt);
? ? ? ? ? ? ?if(mOnScrollChangedListener!=null) {
? ? ? ? ? ? ? ? ? ? mOnScrollChangedListener.onScrollChanged(this, l, t, oldl, oldt);
? ? }
}
publicvoidsetOnScrollChangedListener(OnScrollChangedListener listener) {
? ? ? ? ? ? mOnScrollChangedListener= listener;
}
publicinterfaceOnScrollChangedListener {
? ? ? ? void onScrollChanged(ScrollView who,intl,intt,intoldl,intoldt);
? }
}
**
*? Created by zwr on 2017/3/11.
? ? ?mianactivity去實現(xiàn)接口
*/
publicclassMainActivityextendsAppCompatActivityimplementsChangeAlphaScrollView.OnScrollChangedListener {
privateImageViewimageView;
privateToolbartoolBar;
privatefloatheaderHeight;//頂部高度
privatefloatminHeight;//頂部最低高度,即Bar的高度
privateChangeAlphaScrollViewscrollView;
@Override
protected void onCreate(Bundle savedInstanceState) {
? ? ? super.onCreate(savedInstanceState);
? ? ? setContentView(R.layout.activity_main);
? ? ? imageView= (ImageView) findViewById(R.id.imageView);
? ? ? scrollView= (ChangeAlphaScrollView) findViewById(R.id.myScrollView);
? ? ? toolBar= (Toolbar) findViewById(R.id.tool_bar_home);
? ? ? scrollView.setOnScrollChangedListener(this);
? ? ? getMeasure();
}
@Override
public void onScrollChanged(ScrollView who,intl,intt,intoldl,intoldt) {
? ? ? //得到y(tǒng)軸的偏移量
? ? ?floatscrollY= who.getScrollY();
? ? ?//變化率
? ? ?floatheaderBarOffsetY=headerHeight-minHeight;
? ? ?floatoffset=1- Math.max((headerBarOffsetY-scrollY) /headerBarOffsetY,0f);
? ? ?//Toolbar背景色透明度
? ? ?toolBar.setBackgroundColor(Color.argb((int) (offset*255),255,64,129));//顏色的RGB值
}
//調(diào)用此方法重新測量得到控件高度
private void getMeasure() {
? ? ? ? intw= View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
? ? ? ? inth= View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
? ? ? ? imageView.measure(w,h);
? ? ? ? headerHeight=imageView.getMeasuredHeight();
? ? ? ? toolBar.measure(w,h);
? ? ? ? minHeight=toolBar.getMeasuredHeight();
? }
}
```
注:若有錯誤歡迎指正