7

I'm trying to apply expand collapse feature on Webview Based on its Content height but i'm always getting wrong value Here is my code

public class MesuredHeightWebView extends WebView {
    public MesuredHeightWebView(Context context) {
        super(context);
    }

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

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



    @Override
    public void invalidate() {
        super.invalidate();

        if (getContentHeight() > 0) {
            // WebView has displayed some content and is scrollable.
            if(listener!=null)
                listener.updateContentHeight(getContentHeight());
        }
    }



    WebViewContentHeight listener;

    public void setChangeContentListener(WebViewContentHeight listener) {
        this.listener = listener;
    }
}

and then in the fragment i tried to get the content height

 webView.setWebChromeClient(new WebChromeClient(){
        @Override
        public void onProgressChanged(WebView view, int newProgress) {

            super.onProgressChanged(view, newProgress);
            if(newProgress==100)
            {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        webView.setChangeContentListener(new WebViewContentHeight() {
                            @Override
                            public void updateContentHeight(int height) {

                                if(height>0 && getActivity()!=null) {

                                    System.out.println("the height2 is" + height + " " + Utils.convertPixelsToDp(height, getActivity()));
                                    final int text_height = height;

but my problem is that i'm always getting wrong result Thanks

Antwan
  • 3,837
  • 9
  • 41
  • 62
  • Can you explain why ContentListener must be within a runnable? Can't we get an accurate value if we simply set the listener without it? – Teffi Sep 21 '17 at 08:04

1 Answers1

18

Use the following methods instead of getContentHeight() method:

computeHorizontalScrollRange(); -> for width 
computeVerticalScrollRange(); -> for height

these two methods will return the entire scrollable width/height rather than the actual widht/height of the webview on screen

eyadMhanna
  • 2,412
  • 3
  • 31
  • 49