Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

帶吸附效果的 ViewPager(一):Scroll 視圖吸附入門

編輯:關於 Android 程式設計

什麼叫吸附效果?先看個示例更直觀,借用網上的一張效果圖:

類似效果的 App 很多,網上的實現方法也五花八門,但各種重寫、各種監聽令人不勝其煩。今日突發奇想,順着自己的思路實現了類似效果,不敢獨享,特來分享給大家!

做事得一步一步來,不能一口吃成胖子。知道了原理,接下來就好辦了。所以第一篇,先實現一個簡單的效果,如圖:

實現思路(原理)

1. ScrollView:外層 ScrollView 不必多說。

2. 滑動監聽:要實現這種效果,ScrollView 的滑動監聽必不可少——當 ScrollView 上滑至圖中 snapbar 頂部位置、以及下滑離開該位置時,對吸附控件做相應操作。網上大多通過重寫 View 來實現,我這裡取巧,用「預先在頂部佈置一個控件,靠顯示/隱藏來實現」:上滑到 snapbar 頂部時顯示它,下滑離開時再隱藏,是不是簡單多了?

但有一點要注意:我們需要計算 snapbar 以上部分布局的高度,才能在滑動監聽裡判斷是否滑到了這個位置:

我把這部分高度固定為 160dp,只需把 160dp 轉換成 px 即可。另外,做類似布局時也盡量把頂部這部分高度固定住,方便計算;如果用 wrap_content,就得動態計算高度,相對麻煩。

3. 吸附控件布局:佈局時需要兩個相同的 snapbar,一個跟隨 ScrollView 滑動,一個固定在頂部且初始隱藏。操作方式即第二步所述。

由於 6.0 以前的 SDK 中 ScrollView 無法直接用 onScrollChanged 監聽滑動距離,我們需要稍微重寫一下 ScrollView,並自定義一個接口把 onScrollChanged 事件暴露出來:

package com.byl.snappingviewpager;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;

/**
 * Created by baiyuliang on 2016-5-5.
 */
public class MyScrollView extends ScrollView {
    private ScrollViewListener scrollViewListener = null;

    public MyScrollView(Context context) {
        super(context);
    }

    public MyScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void setScrollViewListener(ScrollViewListener scrollViewListener) {
        this.scrollViewListener = scrollViewListener;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (scrollViewListener != null) {
            scrollViewListener.onScrollChanged(this, x, y, oldx, oldy);
        }
    }

    public interface ScrollViewListener {
        void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy);
    }
}

snapbar 上部高度計算:

snapbar_y = dip2px(this, 160);//注意你的 snapbar 以上部分的高度值,轉換為 px(最好設置為固定值,非固定則要動態計算高度)

/**
 * 將 dp 轉 px
 */
public int dip2px(Context context, float dpValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dpValue * scale + 0.5f);
}

滑動監聽:

scrollView.setScrollViewListener(new MyScrollView.ScrollViewListener() {
    @Override
    public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y >= snapbar_y) {
            rg_snapbar_top.setVisibility(View.VISIBLE);
        } else {
            rg_snapbar_top.setVisibility(View.GONE);
        }
    }
});

就這麼簡單幾步就搞定了!

MainActivity:

package com.byl.snappingviewpager;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    MyScrollView scrollView;
    TextView tv_snapbar_top, tv_snapbar;
    int snapbar_y;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        snapbar_y = dip2px(this, 160);//注意你的 snapbar 以上部分的高度值,轉換為 px(最好設置為固定值,非固定則要動態計算高度)
    }

    private void initView() {
        scrollView = (MyScrollView) findViewById(R.id.scrollView);
        tv_snapbar_top = (TextView) findViewById(R.id.tv_snapbar_top);
        tv_snapbar = (TextView) findViewById(R.id.tv_snapbar);
        scrollView.setScrollViewListener(new MyScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
                if (y >= snapbar_y) {
                    tv_snapbar_top.setVisibility(View.VISIBLE);
                } else {
                    tv_snapbar_top.setVisibility(View.GONE);
                }
            }
        });
        tv_snapbar_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "snapbar_top", Toast.LENGTH_SHORT).show();
            }
        });
        tv_snapbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "snapbar", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 將 dp 轉 px
     */
    public int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}

activity_main.xml(為了方便,列表數據直接寫在布局裡):

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EEEEEE"
    tools:context="com.byl.snappingviewpager.MainActivity">

    <com.byl.snappingviewpager.MyScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        android:scrollbars="none">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="160dp"
                android:background="@color/colorPrimaryDark">
                <ImageView
                    android:id="@+id/iv_headView"
                    android:layout_width="60dp"
                    android:layout_height="60dp"
                    android:layout_centerInParent="true"
                    android:src="@mipmap/ic_launcher" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/iv_headView"
                    android:layout_centerHorizontal="true"
                    android:layout_marginTop="10dp"
                    android:text="白玉梁"
                    android:textColor="#FFFFFF" />
            </RelativeLayout>

            <TextView
                android:id="@+id/tv_snapbar"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:background="#FF6600"
                android:gravity="center_vertical"
                android:paddingLeft="5dp"
                android:textColor="#FFFFFF"
                android:text="snapbar" />

            <!-- 以下為列表內容,為了方便,直接寫在了布局中 -->
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="1dp"
                android:background="#FFFFFF"
                android:orientation="vertical"
                android:padding="10dp">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="標題"
                    android:textColor="#333333"
                    android:textSize="16sp" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    android:text="內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容內容"
                    android:textColor="#666666" />
            </LinearLayout>
            <!-- 其餘列表項結構相同,此處省略 -->
        </LinearLayout>
    </com.byl.snappingviewpager.MyScrollView>

    <TextView
        android:id="@+id/tv_snapbar_top"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:background="#FF6600"
        android:textColor="#FFFFFF"
        android:gravity="center_vertical"
        android:paddingLeft="5dp"
        android:text="snapbar"
        android:visibility="gone" />
</RelativeLayout>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved