Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinearLayout of a WebView and a Button

I recently struggled with an apparently simple Android layout: I wanted a WebView above a Button. It worked fine with the following parameters:

WebView:
  Height: wrap-content
  Weight: unset (by the way, what is the default?)

Button:
  Height: wrap-content
  Weight: unset

However if the web page became too big it spilled out over the button. I tried various combinations of weights and heights, and all except one either completely hide the button, or partially cover it. This is the one that works (copied from http://code.google.com/p/apps-for-android/source/browse/trunk/Samples/WebViewDemo/res/layout/main.xml):

WebView:
  Height: 0
  Weight: 1

Button:
  Height: wrap-content
  Weight: unset

If you change any of those, e.g. give button a weight or change the WebView height to wrap-content then it doesn't work. My question is: Why? Can someone please explain what on Earth the android layout system is thinking?

like image 747
Timmmm Avatar asked Nov 15 '22 11:11

Timmmm


2 Answers

Something like the following should give you what you want. The key is the layout_height="fill_parent" and layout_weight="1" for the WebView.

<LinearLayout android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <WebView android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />

        <Button android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
</LinearLayout>  


Edit: Whoops, I misunderstood your question. It's the layout_weight that makes it not spill over the button (or textview in your example). I'm not sure why it happens, but if there's one "fill_parent" item in your LinearLayout, in addition to one or more "wrap_content" items, you need to specify a layout_weight for the "fill_parent" item, or it'll take over the space for the rest of the widgets.

like image 137
synic Avatar answered Dec 22 '22 21:12

synic


Well I since have understood this. The way the android layout system works is:

  1. All the things are laid out according to their specified height/width.
  2. Any remaining weight is distributed among the views according to their weights.

(Obviously this is never explained.)

Therefore to get it to work you want the button to be wrap-content, which makes it just as big as it needs to be, and the webview to be zero height (since it can shrink to zero). After step 1 you will have the button correct, and then webview zero-height.

Then you set the button weight to 0, and the webview weight to 1, so that any remaining space is given to the webview - i.e. it expands to fill the screen.

Makes perfect sense when you know the algorithm.

like image 38
Timmmm Avatar answered Dec 22 '22 20:12

Timmmm