搜索框上下滑動變透明度是現在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); } } } } }); 源碼下載:http://xiazai.VeVB.COm/201611/yuanma/AndroidSearch(VeVB.COm).rar
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
|
新聞熱點
疑難解答