1. 程式人生 > >android搜尋框上下滑動變色

android搜尋框上下滑動變色

搜尋框上下滑動變透明度是現在APP中很常見的效果;

首先來看下佈局骨架:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="www.sf.com.searchframe.MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--搜尋框-->
    <LinearLayout
        android:id="@+id/ll_search"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#00ab95"
        android:orientation="horizontal">
       ......
    </LinearLayout>

</RelativeLayout>
整體就是一個相對佈局,搜尋框直接覆蓋在listview上面,效果圖最上方的圖片是listview的頭佈局;

這個效果主要用到listview的滑動監聽;

在listview滑動的時候不停的獲取,imageview距離螢幕頂部的距離;

然後獲取到imageview本身的高度;

通過這兩個值判斷imageview是否滑出螢幕,根據不同情況設定搜尋框的透明度;

mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            
            //監聽滑動狀態的改變
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            //用於監聽ListView螢幕滾動
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

                int[] ints = new int[2];
                mImage.getLocationOnScreen(ints);
                /**
                 * mImage距離螢幕頂部的距離(圖片頂部在螢幕最上面,向上滑動為負數,所以取反)
                 * 如果不隱藏狀態列,需要加上狀態列的高度;隱藏狀態列就不用加了;
                 */
                int scrollY = -ints[1]+statusHeight;

                //mImage這個view的高度
                int imageHeight = mImage.getHeight();

                if (mImage != null && imageHeight > 0) {
                    //如果“圖片”沒有向上滑動,設定為全透明
                    if (scrollY < 0) {
                        llSearch.getBackground().setAlpha(0);
                    } else {
                        //“圖片”已經滑動,而且還沒有全部滑出螢幕,根據滑出高度的比例設定透明度的比例
                        if (scrollY < imageHeight) {
                            int progress = (int) (new Float(scrollY) / new Float(imageHeight) * 255);//255
                            llSearch.getBackground().setAlpha(progress);
                        } else {
                            //“圖片”全部滑出螢幕的時候,設為完全不透明
                            llSearch.getBackground().setAlpha(255);
                        }
                    }
                }

            }
        });