WebView和Button的LinearLayout

Tim*_*mmm 5 layout android button webview android-linearlayout

我最近在一个看似简单的Android布局上苦苦挣扎:我想要一个WebView以上的Button.它使用以下参数工作正常:

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

Button:
  Height: wrap-content
  Weight: unset
Run Code Online (Sandbox Code Playgroud)

但是,如果网页变得太大,它会溢出按钮.我尝试了各种重量和高度的组合,除了一个完全隐藏按钮或部分覆盖按钮.这是有效的(从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
Run Code Online (Sandbox Code Playgroud)

如果您更改其中任何一个,例如给按钮增加一个重量或更改WebView高度以包裹内容,那么它就不起作用.我的问题是:为什么?有人可以解释一下android布局系统在想什么吗?

syn*_*nic 3

像下面这样的东西应该会给你你想要的。关键是 WebView 的layout_height =“fill_parent”和layout_weight =“1”。

<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>  
Run Code Online (Sandbox Code Playgroud)


编辑:哎呀,我误解了你的问题。这是layout_weight使其不会溢出按钮(或示例中的textview)。我不确定为什么会发生这种情况,但是如果您的 LinearLayout 中有一个“fill_parent”项,除了一个或多个“wrap_content”项之外,您还需要为“fill_parent”项指定一个layout_weight,否则它将需要覆盖其余小部件的空间。

  • `fill_parent` 将占用 `LinearLayout` 中的所有剩余空间,因此在它后面不能有小部件。总的来说,对于这样的布局,我推荐使用“RelativeLayout”,因为规则更明确,因此更容易维护(您不必记住神奇的“layout_weight”技巧)。只需将“Button”设置为“alignParentBottom”,并将“WebView”设置为“alignParentTop”并位于“Button”之上。 (3认同)