Michele
Michele

Reputation: 6131

Android get WebView height

I have a WebView defined in my XML:

<WebView
    android:id="@+id/streetview_webview"
    android:layout_width="match_parent"
    android:layout_height="164dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/header" />

Now I want to get the height of this WebView inside my code, to exclude the webview scrolling from scrolling my CustomViewPager

@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
    if (childId > 0) {
        View webv = findViewById(R.id.webView1);
        if (webv != null) {
            int x = webv.getLeft();
            int x2 = x + webv.getLayoutParams().width;

            int y = webv.getTop();
            int y2 = y + webv.getMeasuredHeight();

            int targetx = (int) event.getX();
            int targety = (int) event.getY();

            if (targetx > x && targetx < x2 && targety > y && targety < y2) {
                return false;
            }
        }
    }
    return super.onInterceptTouchEvent(event);
}

I have tried

webv.getHitRect but this gets the height of the parent (the whole screen)

webv.getLayoutParams().width; // <- working
webv.getLayoutParams().height; // -1

and

webv.getHeight

But none of them getting me the 164dp height.

edit: Thanks guys Akos Cz is right.

Upvotes: 1

Views: 6214

Answers (2)

Naveen Kumar
Naveen Kumar

Reputation: 989

To get height of webview after the content is loaded then this line of code can help you.

ViewTreeObserver viewTreeObserver  = webview.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {                                
     int height = webview.getMeasuredHeight();
     LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(webview.getLayoutParams());

     if( height != 0 ){
 Toast.makeText(DesignTemplateView.this,"height:"+height,Toast.LENGTH_SHORT).show();
 webview.getViewTreeObserver().removeOnPreDrawListener(this);
    }
      return false;
}
});

Upvotes: 0

Akos Cz
Akos Cz

Reputation: 12790

Try the getMeasuredHeight() method. It is available on all View objects after the measure pass of the layout process.

Take a look at the doc at the following URL for a more detailed explanation, in particular the following sections :

  • Size, padding and margins
  • Layout

http://developer.android.com/reference/android/view/View.html

Upvotes: 3

Related Questions