How to Hide ActionBar/Toolbar While Scrolling Down in Webview

Sathish Kumar picture Sathish Kumar · Feb 27, 2015 · Viewed 24.3k times · Source

In Google chrome and play store. the app can hide the actionbar while scrolling and allows the user to Browse conveniently. Please Help me to do like this.

I've used onTouchListener for webview it doesn't works.

mWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        getSupportActionBar().show();
                            break;
                    case MotionEvent.ACTION_UP:
                        getSupportActionBar().hide();
                            break;
                    default: break;
                }
                return false;
            }
        });

Thanks in Advance

Answer

Dhir Pratap picture Dhir Pratap · Mar 13, 2016

You can do this without any Java code using the design library's CoordinatorLayout and NestedScrollView, with app:layout_scrollFlags set on Toolbar. Here's how you do it.

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>

<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="fill_vertical"
   android:fillViewport="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

You can play around with with different layout_scrollFlags and fitsSystemWindows behaviour once you get the hang of it.