Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/197.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Android中为WebView制作滚动监听器_Android_Webview_Custom Controls_Scrollview - Fatal编程技术网

如何在Android中为WebView制作滚动监听器

如何在Android中为WebView制作滚动监听器,android,webview,custom-controls,scrollview,Android,Webview,Custom Controls,Scrollview,如何在Android中实现WebView的滚动监听器 我尝试了这个,但它没有调用我的日志。我在滚动webview时 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.AbsListV

如何在Android中实现
WebView
的滚动监听器

我尝试了这个,但它没有调用我的
日志。我在滚动webview时

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

}
   }
package com.example.webview.full.width;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.Bundle;
导入android.view.Menu;
导入android.webkit.WebView;
导入android.webkit.WebViewClient;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
进行对话进行对话;
ScorlableWebView wv;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv=(scorlablewebview)findViewById(R.id.scorlablewebview);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().SetBuilTinZoomControl(true);
wv.getSettings().supportZoom();
progressDialog=progressDialog.show(MainActivity.this,
“正在加载书本…!”,“请稍候”);
progressDialog.setCancelable(真);
String htnlString=“for(a=1;a类似于:

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...");
    }
});
wv=(observeWebView)findViewById(R.id.scorlableWebView);
wv.setOnScrollChangedCallback(新的OnScrollChangedCallback(){
Croll上的公共void(int l,int t,int oldl,int oldt){
如果(t>oldt){
//做事
System.out.println(“向上滑动”);
//做事
}
else if(t
自从API 23以来,您就不需要再这样做了,您可以在所有视图上使用新的,包括WebView上。但是,由于您仍然需要支持旧版本,您仍然可以使用@Chris.Jenkins的建议。我对建议的类进行了一些调整,使其与新的OnScrollChangeL“更兼容”istener接口:

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);
}
}
尝试以下操作(查看您想要的所有内容): С创建一个手势检测器,然后创建一个触摸监听器,并设置为滚动视图

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

        }
OnCreate
私人手势检测器;
gestureDetector=新的gestureDetector(此,新
GestureDetector.SimpleOnGestureListener(){
@凌驾
公共布尔onFling(MotionEvent e1、MotionEvent e2、float velocityX、float
速度y){
if(速度y<0){
折叠(FRT);
}否则如果(速度Y>0){
if(frToolBar.getVisibility()==View.GONE)
展开(工具栏);
}
返回super.onFling(e1、e2、velocityX、velocityY);
}
@凌驾
公共布尔onDown(运动事件e){
返回super.onDown(e);
}
});
webView.setOnTouchListener((视图,运动事件)->
gestureDetector.onTouchEvent(motionEvent));
两种方法-
公共静态空间展开(最终视图v){
v、 度量(WindowManager.LayoutParams.MATCH_父项,
indowManager.LayoutParams.WRAP_内容);
//最终int targetHeight=v.getMeasuredHeight();
最终int targetHeight=v.getHeight();
v、 getLayoutParams().height=1;
v、 设置可见性(View.VISIBLE);
动画a=新动画(){
@凌驾
受保护的无效应用转换(浮点插值时间,转换t)
{
v、 getLayoutParams().height=InterpolateTime==1
?WindowManager.LayoutParams.WRAP_内容
:(int)(targetLight*插值时间);
v、 requestLayout();
}
@凌驾
公共布尔值willChangeBounds(){
返回true;
}
};
a、 设定持续时间(300);
v、 startAnimation(a);
}
公共静态空隙塌陷(最终视图v){
最终int initialHeight=v.getMeasuredHeight();
动画a=新动画(){
@凌驾
受保护的无效应用转换(浮点插值时间,转换t)
{
如果(插值时间==1){
v、 设置可见性(View.GONE);
}否则{
v、 getLayoutParams().height=initialHeight-(int)(initialHeight*
插值时间);
v、 requestLayout();
}
}
@凌驾
公共布尔值willChangeBounds(){
返回true;
}
};
a、 设定持续时间(300);
v、 startAnimation(a);
}

以下是更优雅的Kotlin版本的公认答案


class ObservableWebView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {
    var scrollListener: WebViewScrollListener? = null

    override fun onScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
        super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
        when {
            scrollY > oldScrollY -> scrollListener?.onScrollDown()
            scrollY < oldScrollY -> scrollListener?.onScrollUp()
        }
        scrollListener?.onScroll(scrollX, scrollY, oldScrollX, oldScrollY)
    }
}

interface WebViewScrollListener{
    fun onScroll(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int)

    fun onScrollDown()

    fun onScrollUp()
}


类observeWebView@JVM重载构造函数(
上下文:上下文,
属性集?=null,
defStyleAttr:Int=0
):WebView(上下文、属性、defStyleAttr){
var scrollListener:WebViewScrollListener?=null
覆盖有趣的onScrollChanged(scrollX:Int,scrollY:Int,oldScrollX:Int,oldScrollY:Int){
super.onScrollChanged(scrollX、scrollY、oldScrollX、oldScrollY)
什么时候{
scrollY>oldScrollY->scrollListener?.onScrollDown()
scrollYscrollListener?.onScrollUp()
}
scrollListener?.onScroll(scrollX,scrollY,oldScrollX,oldScrollY)
}
}
界面WebViewScrollListener{
有趣的onScroll(scrollX:Int,scrollY:Int,oldScrollX:Int,oldScrollY:Int)
乐趣
乐趣
}
在那里

class ObservableWebView @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {
    var scrollListener: WebViewScrollListener? = null

    override fun onScrollChanged(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int) {
        super.onScrollChanged(scrollX, scrollY, oldScrollX, oldScrollY)
        when {
            scrollY > oldScrollY -> scrollListener?.onScrollDown()
            scrollY < oldScrollY -> scrollListener?.onScrollUp()
        }
        scrollListener?.onScroll(scrollX, scrollY, oldScrollX, oldScrollY)
    }
}

interface WebViewScrollListener{
    fun onScroll(scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int)

    fun onScrollDown()

    fun onScrollUp()
}

webView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
    @Override
    public void onScrollChanged() {
        Log.v(TAG, "+++ scrollchanged "+webView.getScrollY());
    }
});
web.setOnScrollChangeListener(new View.OnScrollChangeListener() {

            @Override
            public void onScrollChange(View p1, int p2, int p3, int p4, int p5)
            {
                Toast.makeText(getApplicationContext, "Scrolled", Toast.LENGTH_SHORT).show();
            }
        });