1. 程式人生 > >Android之scrollview滑動使導航欄漸變背景色

Android之scrollview滑動使導航欄漸變背景色

一:先來效果圖:

-----------------轉載請註明出處:http://blog.csdn.net/android_cll

第一二張效果圖是用紅線標註,第三張為黑線,三張為不同滑動距離的效果圖,不想弄GIF的,湊合看吧、




二:實現步驟:

1.xml實現,在你的佈局加上scrollview,也可以自定義scrollview,都有註釋,就不用解釋太多了、

<com.zjtd.bzcommunity.lib.myScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height=
"wrap_content" android:scrollbars="none"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> </LinearLayout> </com.zjtd.bzcommunity.lib.myScrollView>

2.程式碼實現、

private myScrollView mScrollView; // 整體ScrollView
private int fadingHeight = 600; // 當ScrollView滑動到什麼位置時漸變消失(根據需要進行調整) private Drawable drawable; // 頂部漸變佈局需設定的Drawable private RelativeLayout layout_top_search;//導航欄 private static final int START_ALPHA = 0;//scrollview滑動開始位置 private static final int END_ALPHA = 255;//scrollview滑動結束位置

mScrollView = (myScrollView) view.findViewById(R.id.scrollView
); drawable = getResources().getDrawable(R.color.dhlbg); drawable.setAlpha(START_ALPHA); layout_top_search.setBackgroundDrawable(drawable); //呼叫方法 mScrollView.setOnScrollChangedListener(scrollChangedListener);

 /**
     * ScrollView的滾動監聽
     */
private myScrollView.OnScrollChangedListener scrollChangedListener = new myScrollView.OnScrollChangedListener() {
        @Override
public void onScrollChanged(ScrollView who, int x, int y, int oldx,
                                    int oldy) {
            if (y > fadingHeight) {
                y = fadingHeight; // 當滑動到指定位置之後設定顏色為純色,之前的話要漸變---實現下面的公式即可
//                relativela_id.setBackgroundColor(Color.WHITE);
} else if (y < 0) {
                y = 0;
} else {
//                relativela_id.setBackgroundColor(0x99FFFFFF);
}
            drawable.setAlpha(y * (END_ALPHA - START_ALPHA) / fadingHeight
+ START_ALPHA);
}
    };

---------------------------差不多就是這樣子了,不喜勿噴、