Android如何使用百分比设置布局高度

17

我非常新手并正在练习android。我正在尝试设计一个界面,其中将包含一个背景图像和带有滑动菜单的浮动容器。(更多细节请参见附加的图片)

我的布局包括一个背景图像,一个浮动在底部的带有一些图标的容器,但距底部有一些边距(请参见附加照片)

据我所知,可以通过在底部安排“相对布局”并在其中放置图像来实现此目的。这正确吗?

另外,我想将重复的透明图像添加为浮动div的背景。

请给我一个好建议或指向一个好的教程

提前感谢

输入图像说明

5个回答

38
你可以使用LinearLayout并在xml中设置layout_weight为%。
至于重复的背景,你可以使用tileMode
例如:请注意,weightSum设置为100,以表示总权重将是100。具有layout_weight = 10将给它分配10%的空间分配。
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_gravity="bottom"
    android:weightSum="100">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="10"
        android:background="@drawable/bg"
        android:orientation="horizontal"
        android:tileMode="repeat" >
    </LinearLayout>
    <View 
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="5" />
</LinearLayout>

3
你可以设置 layout_weight=11,它将会占据11%的高度。对于它的父元素,我们需要设置 weightSum=100,就像例子中展示的那样。 - NcJie
1
@ramesh,将layout_gravity="bottom"和layout_marginBottom="20dp"添加到答案的根布局中,并将其放置在FrameLayout中。如果硬编码的20dp不适合您,而您确实想要5%,则可以通过代码计算百分比来设置marginBottom。 - Yaroslav Mytkalyk
总体思路是正确的,但是 weight=10 的意思是它会占用高度的 100 - 10%(即90%)吗?权重越大,它们占用的空间就越少,对吧? - Bakhshi
1
@Bakhshi 注意父布局中有weightSum。因此高度将为<layout_weight>/<weightSum> = 10/100 = 10%,而不是90%。如果未指定weigthSum,则<layout_weight>值将与其兄弟视图归一化为1。 - NcJie

4
您可以使用新的百分比支持库来实现这一点: https://developer.android.com/tools/support-library/features.html#percent 通过进行类似以下的操作:
<android.support.percent.PercentRelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_alignParentBottom="true"
        app:layout_heightPercent="11%"
        app:layout_widthPercent="100%" />

</android.support.percent.PercentRelativeLayout>

1
如果您想将高度按百分比划分,则需要使用方向为水平的线性布局,并为每个项目添加layout_weight。 线性布局指南

0
<view android:layout_width="wrap_content"
      class="net.zel.percentage.PercentageButton"
      android:id="@+id/button"
      android:layout_height="wrap_content"

      customView:percentage_width="50"
      customView:percentage_height="50"

      />

所以你可以在库中添加所需的属性
https://github.com/metrolog3005/percentage_view


0

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