web-dev-qa-db-ja.com

AndroidでWebViewのスクロールリスナーを作成する方法

AndroidでWebViewのスクロールリスナーを実装する方法

これを試しましたが、_Log.i Webビューのスクロール。

package com.example.webview.full.width;
import Android.content.Context;
import Android.util.AttributeSet;
import Android.util.Log;
import Android.webkit.WebView;
import Android.widget.AbsListView;
import Android.widget.AbsListView.OnScrollListener;

public class scorllableWebview extends WebView implements OnScrollListener {


Context ctx;
AttributeSet atrs;

public scorllableWebview(Context context) {
    super(context);

    ctx = context;
}

public scorllableWebview(Context context, AttributeSet atters){
    super(context, atters);

    ctx = context;
    atrs = atters;
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {

    Log.i("onScroll", "Called");
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {


    Log.i("onScrollStateChanged", "Called");

}
}

これが私のMainActivity.Java

package com.example.webview.full.width;
import Android.app.Activity;
import Android.app.ProgressDialog;
import Android.os.Bundle;
import Android.view.Menu;
import Android.webkit.WebView;
import Android.webkit.WebViewClient;
import Android.widget.Toast;

public class MainActivity extends Activity {

ProgressDialog progressDialog;
scorllableWebview wv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (scorllableWebview) findViewById(R.id.scorllableWebview);

    wv.getSettings().setJavaScriptEnabled(true);

    wv.getSettings().setBuiltInZoomControls(true);
    wv.getSettings().supportZoom();

    progressDialog = ProgressDialog.show(MainActivity.this,
            "Loading Book...!", "Please Wait");
    progressDialog.setCancelable(true);

    String htnlString = "<!DOCTYPE html><html><body style = \"text-align:center\"><script type=\"text/javascript\">for(a=1;a<=10;a++)document.write('<img style=\"border-style:dotted;border-width:10px;border-color:black;\"src=\"http://myURL.com/books_snaps/EN567/'+a+'.jpg\" alt=\"Page Not Found\"/>');</script></body></html>";
    // width=\"100%\"
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            progressDialog.dismiss();
            Toast.makeText(MainActivity.this, "Completed",
                    Toast.LENGTH_SHORT).show();
            wv.pageUp(true);
            super.onPageFinished(view, url);
        }

    });

    wv.loadDataWithBaseURL(null, htnlString, "text/html", "UTF-8", null);

}
   }

これが私のXMLファイルです。

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

<com.example.webview.full.width.scorllableWebview
    xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/scorllableWebview"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent" />

</RelativeLayout>
41
Qadir Hussain

何かのようなもの:

public class ObservableWebView extends WebView
{
    private OnScrollChangedCallback mOnScrollChangedCallback;

    public ObservableWebView(final Context context)
    {
        super(context);
    }

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

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

    @Override
    protected void onScrollChanged(final int l, final int t, final int oldl, final int oldt)
    {
        super.onScrollChanged(l, t, oldl, oldt);
        if(mOnScrollChangedCallback != null) mOnScrollChangedCallback.onScroll(l, t, oldl, oldt);
    }

    public OnScrollChangedCallback getOnScrollChangedCallback()
    {
        return mOnScrollChangedCallback;
    }

    public void setOnScrollChangedCallback(final OnScrollChangedCallback onScrollChangedCallback)
    {
        mOnScrollChangedCallback = onScrollChangedCallback;
    }

    /**
     * Impliment in the activity/fragment/view that you want to listen to the webview
     */
    public static interface OnScrollChangedCallback
    {
        public void onScroll(int l, int t, int oldl, int oldt);
    }
}

動作するはずですが、これはテストされていませんが、Androidのほぼすべてのビューで動作します。

次のように実装します。

wv = (ObservableWebView) findViewById(R.id.scorllableWebview);
wv.setOnScrollChangedCallback(new OnScrollChangedCallback(){
    public void onScroll(int l, int t, int oldl, int oldt){
        if(t> oldt){
            //Do stuff
            System.out.println("Swipe UP");
            //Do stuff
        }
        else if(t< oldt){
            System.out.println("Swipe Down");
        }
        Log.d(TAG,"We Scrolled etc...");
    }
});
86
Chris.Jenkins

API 23以降、これを行う必要はありません。WebViewを含むすべてのビューで利用可能な新しい OnScrollChangeListener を使用できます。ただし、古いバージョンをサポートする必要があるため、@ Chris.Jenkinsの提案を引き続き使用できます。新しいOnScrollChangeListenerインターフェイスとの互換性を高めるために、提案されたクラスを調整しました。

public class ObservableWebView extends WebView {
private OnScrollChangeListener onScrollChangeListener;

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

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

public ObservableWebView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
    super.onScrollChanged(l, t, oldl, oldt);
    if (onScrollChangeListener != null) {
        onScrollChangeListener.onScrollChange(this, l, t, oldl, oldt);
    }
}

public void setOnScrollChangeListener(OnScrollChangeListener onScrollChangeListener) {
    this.onScrollChangeListener = onScrollChangeListener;
}

public OnScrollChangeListener getOnScrollChangeListener() {
    return onScrollChangeListener;
}

public interface OnScrollChangeListener {
    /**
     * Called when the scroll position of a view changes.
     *
     * @param v          The view whose scroll position has changed.
     * @param scrollX    Current horizontal scroll Origin.
     * @param scrollY    Current vertical scroll Origin.
     * @param oldScrollX Previous horizontal scroll Origin.
     * @param oldScrollY Previous vertical scroll Origin.
     */
    void onScrollChange(WebView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
}
}
20

これを試してください(必要なすべてのビューに対して):GestureDetectorを作成してからTouchListenerを作成し、スクロールするビューに設定します

OnCreate
         private GestureDetector gestureDetector;
         gestureDetector = new GestureDetector(this, new 
         GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float 
           velocityY) {

                    if (velocityY < 0) {
                        collapse(frToolBar);

                    } else if (velocityY > 0) {
                        if (frToolBar.getVisibility()==View.GONE)
                        expand(frToolBar);
                    }
                    return super.onFling(e1, e2, velocityX, velocityY);
                }

                @Override
                public boolean onDown(MotionEvent e) {
                    return super.onDown(e);
                }
            });

          webView.setOnTouchListener((view, motionEvent) -> 
          gestureDetector.onTouchEvent(motionEvent));


    Two method - 

           public static void expand(final View v) {
            v.measure(WindowManager.LayoutParams.MATCH_PARENT,  
          indowManager.LayoutParams.WRAP_CONTENT);
             // final int targetHeight = v.getMeasuredHeight();
            final int targetHeight = v.getHeight();
            v.getLayoutParams().height = 1;
            v.setVisibility(View.VISIBLE);
            Animation a = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) 
           {
                    v.getLayoutParams().height = interpolatedTime == 1
                            ? WindowManager.LayoutParams.WRAP_CONTENT
                            : (int) (targetHeight * interpolatedTime);
                    v.requestLayout();
                }

                @Override
                public boolean willChangeBounds() {
                    return true;
                }
            };
            a.setDuration(300);
            v.startAnimation(a);

        }


        public static void collapse(final View v) {
            final int initialHeight = v.getMeasuredHeight();
            Animation a = new Animation() {
                @Override
                protected void applyTransformation(float interpolatedTime, Transformation t) 
           {
                    if (interpolatedTime == 1) {
                        v.setVisibility(View.GONE);
                    } else {
                        v.getLayoutParams().height = initialHeight - (int) (initialHeight * 
              interpolatedTime);
                        v.requestLayout();
                    }
                }

                @Override
                public boolean willChangeBounds() {
                    return true;
                }
            };
            a.setDuration(300);
            v.startAnimation(a);

        }
0
Andrij Kan