如何在android中获取Webview的宽度和高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1612628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:20:46  来源:igfitidea点击:

How to get width and height of a Webview in android

androidandroid-widget

提问by mini

I want to determine the width and the height of the WebView. I have already tried it using:

我想确定WebView. 我已经尝试过使用:

webView.getWidth();
webView.getHeight();

but the resulting log always shows them to be 0.

但结果日志总是显示它们为 0。

回答by gawicks

Here's a more elegant solution

这是一个更优雅的解决方案

public void onCreate(Bundle savedInstanceState) {


        webView = (WebView) findViewById(R.id.webView1);

        webView.addOnLayoutChangeListener(new OnLayoutChangeListener() {

            @Override
            public void onLayoutChange(View v, int left, int top, int right,int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                 int w= webView.getWidth();
                 int h= webView.getHeight();


            }
        });



    }   

回答by Roko

For anyone else who still struggles. Use these methods to get the height and the width of your webview.

对于任何仍在奋斗的人。使用这些方法来获取 webview 的高度和宽度。

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

回答by agodinhost

The onPageFinishedcall back approach does not work when using loadDataor loadDataWithBaseURL. I saw another solution on Andromedevusing JavaScript, but I'm not convinced that this is the best path to take.

onPageFinished使用时,回拨方法不起作用loadData或者loadDataWithBaseURL。我在Andromedev上看到了另一个使用 JavaScript 的解决方案,但我不相信这是最好的选择。

回答by Bostone

Hmmm - I looked through the WevView source and I can see that internally they are using View#getWidth and View#getHeight here's one of the WebView's private methods:

嗯 - 我查看了 WevView 源代码,我可以看到他们在内部使用 View#getWidth 和 View#getHeight 这是WebView的私有方法之一:

/*
 * Return the width of the view where the content of WebView should render
 * to.
 */
private int getViewWidth() {
    if (!isVerticalScrollBarEnabled() || mOverlayVerticalScrollbar) {
        return getWidth();
    } else {
        return getWidth() - getVerticalScrollbarWidth();
    }
}

As noted in the comments you have to make sure you are measuring it after you assign the activity layout e.g. setContentView(R.layout.mylayout);

如评论中所述,您必须确保在分配活动布局后对其进行测量,例如 setContentView(R.layout.mylayout);

回答by espinchi

You were probably checking for the sizes too soon, most likely in the onCreate. Instead, try this:

您可能过早地检查尺寸,很可能在onCreate. 相反,试试这个:

webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String url) {
                super.onPageFinished(webView, url);
                Log.i(TAG, findViewById(R.id.my_component).getWidth(););
            }
        });

回答by espinchi

you are checking size of webview too early. you can try this in following method

您过早地检查 webview 的大小。你可以用下面的方法试试这个

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
            webView.getWidth();
            webView.getHeight();
}

回答by Jon Goodwin

You need the width and height of the WebView CONTENTS, after you loaded your HTML. YES you do, but there is no getContentWidth method (only a view port value), AND the getContentHeight() is inaccurate !

加载 HTML 后,您需要 WebView CONTENTS 的宽度和高度。是的,您这样做了,但是没有 getContentWidth 方法(只有一个视图端口值),并且 getContentHeight() 不准确!

Answer: sub-class WebView:

答:子类WebView:

/*
  Jon Goodwin
*/
package com.example.html2pdf;//your package

import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebView;

class CustomWebView extends WebView
{
    public int rawContentWidth   = 0;                         //unneeded
    public int rawContentHeight  = 0;                         //unneeded
    Context    mContext          = null;                      //unneeded

    public CustomWebView(Context context)                     //unused constructor
    {
        super(context);
        mContext = this.getContext();
    }   

    public CustomWebView(Context context, AttributeSet attrs) //inflate constructor
    {
        super(context,attrs);
        mContext = context;
    }

    public int getContentWidth()
    {
        int ret = super.computeHorizontalScrollRange();//working after load of page
        rawContentWidth = ret;
        return ret;
    }

    public int getContentHeight()
    {
        int ret = super.computeVerticalScrollRange(); //working after load of page
        rawContentHeight = ret;
        return ret;
    }
//=========
}//class
//=========

回答by Morse

I used a work-around , instead of fetching from unreliable webview get from DisplayMetrics, assuming you have webview width almost equal to phone screen size and height almost equal to height of phone screensize.

我使用了一种解决方法,而不是从 DisplayMetrics 中获取不可靠的 webview,假设您的 webview 宽度几乎等于手机屏幕尺寸,高度几乎等于手机屏幕尺寸的高度。

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = (int) displayMetrics.heightPixels*0.9;
int width = displayMetrics.widthPixels;

回答by fahad_sust

If you want to get the original height after loading content, you can use the below code. Though the code is deprecated, yet it works perfectly.

如果您想在加载内容后获取原始高度,可以使用以下代码。虽然代码已被弃用,但它运行良好。

webview.setPictureListener(new WebView.PictureListener() {
        @Override
        public void onNewPicture(WebView webView, @Nullable Picture picture) {
            int height = webview.getContentHeight();
            int height1 = webview.getMeasuredHeight();
            int height2 = webview.getHeight();
        }
    });

回答by Gor

I had the same problem. I just put initWebViewmethod in onWindowFocusChangedt.

我有同样的问题。我只是将initWebView方法放在onWindowFocusChangedt 中

public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    initWebView();
}


private void initWebView(){
    if(isOnline()){
        venueWebView = (WebView) findViewById(R.id.venueWebView);
        String url = "some url";
        int viewWight = venueWebView.getWidth();
        int viewHeight = venueWebView.getHeight();
        venueWebView.loadUrl(url);
    }