Android:布局高度以屏幕分辨率的百分比为单位

7
我在Android方面还很新,所以这可能是一个愚蠢的问题,但我还是想问一下。我有一个Activity的RelativeLayout布局,在这个布局中我有另一个布局位于屏幕底部。有时我会隐藏它或使其可见,这并不重要。是否可以使另一个布局的高度占总屏幕高度的27%?我的想法是保留屏幕上除此布局之外的其他内容。有人尝试过类似这样的操作吗?

你的意思是说你想要屏幕的两个部分 - 顶部占据屏幕的73%,底部占据27%吗?还是你想要一个视图坐在另一个视图内,当可见时覆盖父视图的底部27%? - brianestey
2个回答

24

LinearLayout可以通过android:layout_weight属性实现此功能。例如,下面是一个包含三个Button的布局,分别占高度的50%,30%和20%:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="50"
        android:text="@string/fifty_percent"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="30"
        android:text="@string/thirty_percent"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="20"
        android:text="@string/twenty_percent"/>

</LinearLayout>

然而,您不能简单地声明布局文件中任意位置的任意小部件应占屏幕大小的任意百分比。但是您可以在Java中执行该计算,并根据需要调整小部件的LayoutParams


1
你可以尝试这个,它更复杂但有用。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name" />

<LinearLayout
    android:id="@+id/parent_of_bottom_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_alignParentBottom="true" >

    <LinearLayout
        android:id="@+id/content_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="27">

       //Add your content here

   </LinearLayout>
</LinearLayout>


你能详细说明一下这个是如何工作的,以及为什么它能够回答这个问题吗? - Ro Yo Mi
你不能在RelativeLayout中使用android:layout_weight,所以我使用了一个LinearLayout来使权重在相对布局中成比例,我从我的代码项目中找到了解决方案,所以我分享了它。 - wSakly
谢谢,这是一个有趣的解决问题的方法。 - Ro Yo Mi
没事,这是给安卓朋友们的。 - wSakly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接