【问题标题】:Set width of parent linear layout as percentage of the screen将父线性布局的宽度设置为屏幕的百分比
【发布时间】:2015-02-25 11:38:50
【问题描述】:

我正在构建一个 android 应用程序,并且我有一个对话框片段。对话框片段具有设定的宽度。但是,问题是当应用在具有不同屏幕尺寸的设备上运行时,对话框片段没有正确居中。

最初,我拥有的是:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="500dp"
  android:layout_height="wrap_content">

  <-- code goes here -->

</RelativeLayout>

如您所见,我有一个定义宽度的 relativeLayout。因为我知道你不能在相对布局中使用layout_weight,所以我所做的就是将父相对布局包装在线性布局中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="0.8"
    android:weightSum="1">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

    </RelativeLayout>
</LinearLayout>

但是,这不起作用,因为当我在屏幕尺寸较小的设备上运行应用程序时,对话框片段会被剪切。

如何将对话框片段的宽度设置为屏幕大小的百分比?这有可能吗,还是我必须求助于以编程方式设置它?

【问题讨论】:

  • 如果您将 RelativeLayout android:layout_width 设置为 match_parent 它应该很好地集中在所有设备上
  • 设置重心
  • @Marcus,即使relativeLayout的宽度大于设备的宽度?我对此表示怀疑。
  • 如果您将其设置为match_parent@Razgriz,它将永远不会更大

标签: android android-layout android-dialogfragment android-percent-library


【解决方案1】:

这是一个正确的方法,如果你想让RelativeLayout有40%的屏幕宽度,但是这个技术不能应用于父布局,因为父布局没有父布局并且android:layout_weight不影响

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="100">

<RelativeLayout
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="40">

</RelativeLayout>

因为我知道你不能在相对布局中使用 layout_weight

我们可以在任何视图和布局中使用 layout_weight,如果它是 LinearLayout 的直接子级

【讨论】:

  • 在你的情况下它是一个 schemas.android.com/apk/res/android"...,这个布局没有父布局,所以在其中使用 android:layout_height 没有效果
【解决方案2】:

借助新的百分比支持库,您现在可以使用PercentRelativeLayout

Check out this link

【讨论】:

    【解决方案3】:

    下面的代码将使相对布局成为父级的 1/2,并将其水平居中放置:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal">
    
        <RelativeLayout
            android:layout_width="0dp"
            android:layout_weight="0.5"
            android:layout_height="wrap_content">
    
        </RelativeLayout>
    </LinearLayout>
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-07
      • 2011-03-02
      • 2013-03-28
      • 1970-01-01
      • 2017-05-07
      • 2017-08-24
      • 2012-02-05
      • 2012-08-31
      相关资源
      最近更新 更多