Layout_weight以任意方式划分

时间:2018-02-11 06:39:59

标签: android android-layout-weight

android:layout_weight beginner's question

Understanding weight and layout_weight, the bigger layout_weight is, more it shrinks in the layout.

这两个链接都发布了类似的问题,但这些解决方案并没有帮助我。

xml代码:

app.UseAuthentication()

因此,如果我将总重量设为10,并将其除以7:3的比例,那么我会得到这种不均匀的布局。可以看出,权重为7的那个看起来比3的那个小。我还尝试设置layout_height = 0px或layout_width = 0px。在这种情况下,布局缩小为0. Where weight ratio are 7:3 enter image description here

With layout_height = 0 enter image description here

2 个答案:

答案 0 :(得分:1)

第1步

创建一个新项目并打开xml布局文件,在LinearLayout(水平)上拖动,并在线性布局中添加两个按钮。

您的布局文件现在应该看起来像右侧的图像。

注意按钮是如何向左聚集的,这是权重有用的地方。

enter image description here

第2步

现在切换到文本视图,并给予LinearLayout(水平)一个100的weightSum。

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:weightSum="100">

第3步

现在为每个按钮添加一个layout_weight属性,使值为50。

<Button
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="New Button"
       android:id="@+id/button"
       android:layout_weight="50"/>

第4步

现在,如果再次查看显示屏,按钮应均匀分开。

一种思考如何工作的方法是将weightSum视为可用空间的100%,而layout_weight是该元素占100%的百分比。

由于我们给按钮每个重量为50,因此两者都占用了50%的空间。

我们也可以将weightSum设为1,并且给出按钮layout_weight为0.5以获得相同的效果。

enter image description here

希望它对你有用:)

答案 1 :(得分:0)

要获得layout_weight效果,您必须让layout_heightwrap_content

   <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal"></LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:orientation="horizontal"></LinearLayout>
相关问题