web-dev-qa-db-ja.com

Webviewで下にスクロールしているときにActionBar / Toolbarを非表示にする方法

Google chromeおよびPlayストアでは、アプリはスクロール中にアクションバーを非表示にすることができ、ユーザーが便利にブラウジングできるようにします。このようにするために私を助けてください。

それが機能しないwebviewのonTouchListenerを使用しました。

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;
            }
        });

前もって感謝します

18
Sathish Kumar

Javaコードなしでこれを行うには、設計ライブラリのCoordinatorLayoutおよびNestedScrollViewを使用します。app:layout_scrollFlagsToolbarに設定しました。方法は次のとおりです。

<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"
    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>

慣れてきたら、さまざまなlayout_scrollFlagsとfitsSystemWindowsの動作をいじってみてください。

48
Dhir Pratap

さて、私はCustomWebViewGestureDetectorによって実装しました:

CustomWebView.Java

public class CustomWebView extends WebView {
    private GestureDetector gestureDetector;
    public CustomWebView(Context context) {
        super(context);
    }
    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return gestureDetector.onTouchEvent(ev) || super.onTouchEvent(ev);
    }

    public void setGestureDetector(GestureDetector gestureDetector) {
        this.gestureDetector = gestureDetector;
    }
}

web_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:background="@Android:color/transparent"
    Android:orientation="vertical">

   <com.customview.CustomWebView
            Android:id="@+id/customWebView"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            Android:focusable="true" />

</LinearLayout>

CustomeGestureDetectorジェスチャー検出のclss(私はフラグメントに追加しました):

private class CustomeGestureDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if(e1 == null || e2 == null) return false;
            if(e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false;
            else {
                try {
                    if(e1.getY() - e2.getY() > 20 ) {
                            // Hide Actionbar
                        getSupportActionBar().hide();
                        customWebView.invalidate();
                       return false;
                    }
                    else if (e2.getY() - e1.getY() > 20 ) {
                            // Show Actionbar
                        getSupportActionBar().show();
                        customWebView.invalidate();
                       return false;
                    }

                } catch (Exception e) {
                    customWebView.invalidate();
                }
                return false;
            }


        }
    }

WebFragment.Java

private CustomWebView customWebView;

customWebView= (CustomWebView) view.findViewById(R.id.customWebView);

customWebView.setGestureDetector(new GestureDetector(new CustomeGestureDetector()));

私にとってはうまくいきます。

17
Hiren Patel

enter image description here

package com.keshav.hideactionbarandfooterexample;

import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.support.v7.widget.LinearLayoutManager;
import Android.support.v7.widget.RecyclerView;
import Android.support.v7.widget.Toolbar;
import Android.util.Log;
import Android.view.View;
import Android.view.animation.AccelerateInterpolator;
import Android.view.animation.DecelerateInterpolator;
import Android.widget.FrameLayout;
import Android.widget.ImageButton;

import Java.util.ArrayList;
import Java.util.List;

import adapters.RecyclerAdapter;
import listners.HidingScrollListener;

public class MainActivity extends AppCompatActivity {

    private Toolbar mToolbar;
    private Toolbar toolbar_bottom;
    private ImageButton mFabButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppThemeRed);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.e("keshav", "MainActivity called");

        initToolbar();
        mFabButton = (ImageButton) findViewById(R.id.fabButton);
        initRecyclerView();
    }

    private void initToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar_bottom = (Toolbar) findViewById(R.id.toolbar_bottom);
        setSupportActionBar(mToolbar);
        setSupportActionBar(toolbar_bottom);
        setTitle(getString(R.string.app_name));
        mToolbar.setTitleTextColor(getResources().getColor(Android.R.color.white));
        toolbar_bottom.setTitleTextColor(getResources().getColor(Android.R.color.white));


        toolbar_bottom.setVisibility(View.GONE);
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RecyclerAdapter recyclerAdapter = new RecyclerAdapter(createItemList());
        recyclerView.setAdapter(recyclerAdapter);

        recyclerView.addOnScrollListener(new HidingScrollListener() {
            @Override
            public void onHide() {
                hideViews();
            }

            @Override
            public void onShow() {
                showViews();
            }
        });
    }

    private void hideViews() {
        // TODO (-mToolbar)  plus means  2 view above ho jaye or not visible to user
        mToolbar.animate().translationY(-mToolbar.getHeight()).setInterpolator(new AccelerateInterpolator(2));

        // TODO uncomment this Hide Footer in Android when Scrolling
        // TODO (+mToolbar)  plus means  2 view forward ho jaye or not visible to user
        toolbar_bottom.animate().translationY(+toolbar_bottom.getHeight()).setInterpolator(new AccelerateInterpolator(2));

        // TODO keshav Hide Also Floatng Button In Android
        FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mFabButton.getLayoutParams();
        int fabBottomMargin = lp.bottomMargin;
        mFabButton.animate().translationY(mFabButton.getHeight() + fabBottomMargin).setInterpolator(new AccelerateInterpolator(2)).start();
        // TODO keshav Hide Also Floatng Button In Android
    }

    private void showViews() {
        mToolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));

        // TODO uncomment this Hide Footer in Android when Scrolling
        toolbar_bottom.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
        mFabButton.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2)).start();
    }

    private List<String> createItemList() {
        List<String> itemList = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            itemList.add("Item " + i);
        }
        return itemList;
    }
}

=============================================
             RecyclerAdapter
=============================================
package adapters;

import Android.content.Context;
import Android.support.v7.widget.RecyclerView;
import Android.view.LayoutInflater;
import Android.view.View;
import Android.view.ViewGroup;

import com.keshav.hideactionbarandfooterexample.R;

import Java.util.List;

/*
* RecyclerView Adapter that allows to add a header view.
* */
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private static final int TYPE_HEADER = 2;
    private static final int TYPE_ITEM = 1;
    private List<String> mItemList;

    public RecyclerAdapter(List<String> itemList) {
        mItemList = itemList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        if (viewType == TYPE_ITEM) {
            final View view = LayoutInflater.from(context).inflate(R.layout.recycler_item, parent, false);
            return RecyclerItemViewHolder.newInstance(view);
        } else if (viewType == TYPE_HEADER) {
            final View view = LayoutInflater.from(context).inflate(R.layout.recycler_header, parent, false);
            return new RecyclerHeaderViewHolder(view);
        }
        throw new RuntimeException("There is no type that matches the type " + viewType + " + make sure your using types correctly");
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (!isPositionHeader(position)) {
            RecyclerItemViewHolder holder = (RecyclerItemViewHolder) viewHolder;
            String itemText = mItemList.get(position - 1); // header
            holder.setItemText(itemText);
        }
    }

    public int getBasicItemCount() {
        return mItemList == null ? 0 : mItemList.size();
    }


    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position)) {
            return TYPE_HEADER;
        }

        return TYPE_ITEM;
    }

    @Override
    public int getItemCount() {
        return getBasicItemCount() + 1; // header
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}

=====================================================
         RecyclerHeaderViewHolder
=====================================================
package adapters;

import Android.support.v7.widget.RecyclerView;
import Android.view.View;

public class RecyclerHeaderViewHolder extends RecyclerView.ViewHolder {
    public RecyclerHeaderViewHolder(View itemView) {
        super(itemView);
    }
}

=====================================================
              RecyclerItemViewHolder
=====================================================

package adapters;

import Android.support.v7.widget.RecyclerView;
import Android.view.View;
import Android.widget.TextView;

import com.keshav.hideactionbarandfooterexample.R;


public class RecyclerItemViewHolder extends RecyclerView.ViewHolder {

    private final TextView mItemTextView;

    public RecyclerItemViewHolder(final View parent, TextView itemTextView) {
        super(parent);
        mItemTextView = itemTextView;
    }

    public static RecyclerItemViewHolder newInstance(View parent) {
        TextView itemTextView = (TextView) parent.findViewById(R.id.itemTextView);
        return new RecyclerItemViewHolder(parent, itemTextView);
    }

    public void setItemText(CharSequence text) {
        mItemTextView.setText(text);
    }

}

===================================================
            activity_main.xml
===================================================

<FrameLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
                Android:layout_width="match_parent"
                Android:layout_height="match_parent">

    <Android.support.v7.widget.RecyclerView
            Android:id="@+id/recyclerView"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"/>

    <Android.support.v7.widget.Toolbar
            Android:id="@+id/toolbar"
            Android:layout_width="match_parent"
            Android:layout_height="?attr/actionBarSize"
            Android:background="?attr/colorPrimary"/>

    <ImageButton
            Android:id="@+id/fabButton"
            Android:layout_width="56dp"
            Android:layout_height="56dp"
            Android:layout_gravity="bottom|right"
            Android:layout_marginBottom="16dp"
            Android:layout_marginRight="16dp"
            Android:background="@drawable/fab_bcg"
            Android:src="@drawable/ic_favorite_outline_white_24dp"
            Android:contentDescription="@string/fab_description"/>


    <RelativeLayout
        Android:layout_width="match_parent"
        Android:layout_height="match_parent">

    <Android.support.v7.widget.Toolbar
        Android:id="@+id/toolbar_bottom"
        Android:layout_width="match_parent"
        Android:layout_alignParentBottom="true"
        Android:layout_height="?attr/actionBarSize"
        Android:background="?attr/colorPrimary"/>

    </RelativeLayout>

</FrameLayout>


==================================================
    recycle_header.xml in layout folder
==================================================

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:Android="http://schemas.Android.com/apk/res/Android"
      Android:layout_width="match_parent"
      Android:layout_height="?attr/actionBarSize"/>

==================================================
    recycle_item.xml in layout folder
==================================================
<?xml version="1.0" encoding="utf-8"?>
<Android.support.v7.widget.CardView xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:card_view="http://schemas.Android.com/apk/res-auto"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center"
    Android:layout_margin="8dp"
    card_view:cardCornerRadius="4dp">
    <TextView
        Android:id="@+id/itemTextView"
        Android:layout_width="match_parent"
        Android:layout_height="?attr/listPreferredItemHeight"
        Android:gravity="center_vertical"
        Android:padding="8dp"
        style="@style/Base.TextAppearance.AppCompat.Body2"/>
</Android.support.v7.widget.CardView>


=================================================
                      styles.xml
=================================================
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    </style>

    <style name="AppThemeRed" parent="AppTheme">
        <item name="colorPrimary">@color/color_primary_red</item>
        <item name="colorPrimaryDark">@color/color_primary_red_dark</item>
    </style>

    <style name="AppThemeGreen" parent="AppTheme">
        <item name="colorPrimary">@color/color_primary_green</item>
        <item name="colorPrimaryDark">@color/color_primary_green_dark</item>
    </style>

    <style name="AppThemeBlue" parent="AppTheme">
        <item name="colorPrimary">@color/color_primary_blue</item>
        <item name="colorPrimaryDark">@color/color_primary_blue_dark</item>
        <item name="colorAccent">@color/color_accent_pink</item>
    </style>

</resources>

build.gradle依存関係

  compile 'com.Android.support:appcompat-v7:25.3.1'
    compile 'com.Android.support:recyclerview-v7:25.3.1'
    compile 'com.Android.support:cardview-v7:25.3.1'
    compile 'com.Android.support:design:25.3.1'
2
Keshav Gera