在公司項目中用到了導航欄吸頂效果,大致界面如下,當scrollview向上滑動到tab導航欄緊靠標題欄時懸浮靜止,再向下滑動可恢復到原來位置。
公司項目不便展示,發現酷狗有這種效果,便錄製下來:
ok,就這樣的效果。
原理很簡單,(看着第一張圖)滑動scrollview當:
導航欄距屏幕頂部的距離小於等於標題欄的高度時 懸浮,即上滑到緊貼標題欄時 懸浮。
反之:
(導航欄原來的位置)下滑到距離大於標題欄的高度時將懸浮的導航欄放回原來的位置。
是不是很超級簡單,是不是?。嗯,說“是”的同學你可以走了,拍桌的同學先不要激動,我不是問你們,凳子放下坐好來。
接下來我要一步一步放代碼了。
首先是xml佈局,大致醬紫,不重要的view都已省略:
<LinearLayout 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"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--自定義下面scrollview 設置滑動監聽方法-->
<MyScrollView
android:id="@+id/myScrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true"
android:focusable="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="vertical">
<!--此處省略頭部view-->
<!--下面LinearLayout用於包裹導航欄控件-->
<LinearLayout
android:id="@+id/line_add_navigation_fixation"
android:layout_width="match_parent"
android:layout_height="填寫固定的導航欄高度"
android:background="@color/white"
android:orientation="vertical">
<!--此處省略導航欄view-->
</LinearLayout>
<ViewPager
android:id="@+id/viewPage_device"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</MyScrollView>
<!--下面LinearLayout用於佔位-->
<LinearLayout
android:id="@+id/line_add_navigation_suspension"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="vertical">
</LinearLayout>
</FrameLayout>
</LinearLayout>
然後是java代碼,
主要代碼:
//scrollview的滑動監聽
@Override
public void onScrollChanged(MyScrollView ceshimy, int scrollX, int scrollY, int oldl, int oldt) {
int[] location = new int[2];
lineAddNavigationFixation.getLocationOnScreen(location);
//lineAddNavigationFixation是包裹導航欄的LinearLayout
int y = location[1];//導航欄距屏幕頂部的距離,會隨着scrollview的滑動而改變
if (y <= titleView.getHeight()) {//導航欄距屏幕頂部的距離小於等於標題欄的高度時 懸浮,即上滑到緊貼標題欄時 懸浮
addNavigationSuspension();
} else {//反之下滑到距離大於標題欄的高度時放回原來的位置
addNavigationFixation();
}
}
private void addNavigationSuspension() {//添加懸浮
//lineAddNavigationSuspension是佈局中的佔位LinearLayout
if (lineAddNavigationSuspension.getChildCount() == 0) {
if (navigationDevice.getParent() != null)
((ViewGroup) navigationDevice.getParent()).removeView(navigationDevice);
lineAddNavigationSuspension.addView(navigationDevice);
}
}
private void addNavigationFixation() {//懸浮固定到原位置
if (lineAddNavigationFixation.getChildCount() == 0) {
// L.e("---" + "固定");
if (navigationDevice.getParent() != null)
((ViewGroup) navigationDevice.getParent()).removeView(navigationDevice);
lineAddNavigationFixation.addView(navigationDevice);
}
}
完成,簡單吧。enmmm