6

Is there any way to prevent an Android WebView from scrolling its content to the top when it receives a requestFocus ?

I need to manipulate several layers in an Activity, changing the focus between them. However, using requestFocus to move the focus back to the WebView always causes the WebView to jump to the top of the HTML page it is displaying. While I can reposition it afterwards, doing so throws off the order of other events being processed and thus adds significant further complexity to that code. The MUCH simpler solution would be to just prevent the WebView from repositioning its content content on what should just be a simple focus change. Is there a way to do this? (I've tried overriding onOverScrolled and onScrollChanged, but these don't seem to be called by the scrolling that is being done by the WebView on requestFocus.)

BillB
  • 331
  • 3
  • 8

2 Answers2

4

After many attempts

WebSettings webSettings = mWebView.getSettings();
webSettings.setNeedInitialFocus(false);

the setNeedInitialFocus(false) may solve the problem.

likaci
  • 491
  • 1
  • 4
  • 12
0

Override scrollTo in WebView:

public class MyWebView extends WebView{
    public boolean requestingFocus = false;  // requestFocus() is executing at the moment

    @Override
    public void scrollTo(int x, int y){
        if(requestingFocus)  // ignore such call
            requestingFocus = false;
        else
            super.scrollTo(x, y);
    }
}

And when calling requestFocus(), add this line:

myWebView.requestingFocus = true;
myWebView.requestFocus();

So, scrollTo call, which scrolls WebView to the top, will be ignored.

Lev Leontev
  • 2,538
  • 2
  • 19
  • 31