【问题标题】:Android set layout_weight to width in vertical LinearLayoutAndroid在垂直LinearLayout中将layout_weight设置为宽度
【发布时间】:2016-12-20 18:27:18
【问题描述】:

我有一个垂直的 LinearLayout,其中有一个按钮。我想将此按钮设为 LinearLayout 宽度的 70% 并将其居中。

我尝试将layout_weight设置为0.7,同时将layout_width设置为0,但由于是垂直LinearLayout,不影响宽度,只会影响高度。

如何在垂直布局中更改宽度的权重?我是否必须为按钮添加一个嵌套的水平 LinearLayout 以便我可以设置它的权重?

【问题讨论】:

  • 把你的xml代码发给我。
  • 和其他 30% 的布局你必须给 0dp 宽度和 0.3 重量。
  • 发布您的 XML 代码。
  • 嵌套水平线性布局对我来说似乎是唯一的选择

标签: android android-layout android-layout-weight


【解决方案1】:

尝试使用新的PercentRelativeLayout,你可以在没有嵌套布局的情况下实现你想要的。

将此包含在您的依赖项中:com.android.support:percent:25.1.0

然后在你的代码中

<android.support.percent.PercentRelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
  ...

 <Button
       app:layout_widthPercent="70%"
       android:layout_height="wrap_content"/>
  ...

</android.support.percent.PercentRelativeLayout>

【讨论】:

  • 是否有百分比线性布局?
  • 我知道我可以告诉小部件到另一个小部件下方,但我试图避免它,只是让布局像线性布局一样自行设置
  • 你为什么要避免它?它与 linearLayout 相同,但您需要指定它
  • 只是为了以后工作更舒服。显然我现在可以做到,但只是为了将来保存一些著作。
【解决方案2】:
linearLayout -> orientation = horizontal
button -> layout width = 0dp
       -> layout height = wrap_content
       -> layout weight = 1

【讨论】:

  • 但我需要垂直布局,而不是水平布局
  • 您可以尝试将按钮的宽度设置为match_parent,并添加左右边距,或者使用嵌套布局
  • 这样设置两边的边距是否被认为是一种好习惯?
【解决方案3】:

请检查一下。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.7"
    android:gravity="center"
    android:orientation="vertical">
    <Button
        android:id="@+id/yourRequiredButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </LinearLayout>

    <Button
        android:id="@+id/container"
        android:layout_weight="0.3"
        android:layout_width="match_parent"
        android:layout_height="0dp" />

</LinearLayout>

【讨论】:

    【解决方案4】:

    试试这个:

    <LinearLayout>
        <Space android:layout_weight=0.15/>
        <Button android:layout_weight=0.7/>
        <Space android:layout_weight=0.15/>
    </LinearLayout>
    

    https://developer.android.com/reference/android/widget/Space.html

    我还建议您将值放入dimens.xml 文件中。

    【讨论】:

      猜你喜欢
      • 2011-12-18
      • 1970-01-01
      • 2021-09-07
      • 2017-07-28
      • 2011-04-11
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      相关资源
      最近更新 更多