Rishit Dagli
Rishit Dagli

Reputation: 1006

Cropping WebViews in Android

I have a WebView that loads the web page using the standard invocation.

The Kotlin code I used-

myWebView.settings.javaScriptEnabled = true

val projectUrl: String = "Web page URL"
myWebView.loadUrl(projectUrl)

With this, I am able to see my web page well, what I want to do is crop the webpage something like not showing the top 20 pixels or bottom 20 pixels of my loaded web page. How could I do this?

I would give more preference to an authentic solution but I am also fine in implementing a hack for this.

Upvotes: 1

Views: 809

Answers (3)

Gines Frank Ellis
Gines Frank Ellis

Reputation: 11

I used the marginTop as you can see here and set it to -150dp so it will crop the webview above:

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="-150dp" />

You will see something like this on your design, it's like having an invisible imageline:

Design margin indicator

Once the app reloads you may now not see the croped area and not allowed to scrolled on that particular area.

Upvotes: 1

ABDELRAHMAN Khaled
ABDELRAHMAN Khaled

Reputation: 43

You can debug the app and log the scroll y-pos to decide the desired area you want the user to scroll between and if the user exceeds this area back him back so in this example from 0 to 135 it's not desired header for me to show so I prevent the user from scrolling in y-pos lower than 135 and after 6600 and don`t want the user to see the content so I do the same process

// first scroll to hide the header
    webView.scrollTo(0 , 135);
// listen for the user scroll to prevent him from scrolling on a hidden area
    webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if(scrollY<135) webView.scrollTo(scrollX , 135);
                    if(scrollY>6600) webView.scrollTo(scrollX , 6600);
                }
            });

Upvotes: 0

SimpleJack
SimpleJack

Reputation: 181

I would ask for more detail why you would ever want to do something like this? Sounds like an issue that should be sorted on the webpage design side.

Hack: Could I suggest you just place two opaque views over the top of your webview and then programatically set the transparency/height to your preference?

Upvotes: 1

Related Questions