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?
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.
Well I since have understood this. The way the android layout system works is:
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With