首先,这不是一个重复的问题,我尽我所能尝试了所有(有很多)类似的问题。此类问题的解决方案似乎非常主观,特定于给定场景。
我的布局当前如下所示。黑框是图像(分别是 Logo 和正文),颜色代表每个布局:
我的 XML:
<?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:background="#000"
android:padding="0px"
android:layout_margin="0px"
android:orientation="vertical">
<LinearLayout
android:layout_weight="16"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:gravity="top|center"
android:orientation="horizontal">
<ImageView
android:id="@+id/logo"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/logo"
android:layout_gravity="top|center" />
</LinearLayout>
<LinearLayout
android:layout_weight="4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00F"
android:gravity="bottom|left"
android:orientation="vertical">
<ImageView
android:id="@+id/body"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/body"
android:layout_gravity="bottom|left" />
</LinearLayout>
</LinearLayout>
在这里您可以看到我有一个父线性布局,分为两个子线性布局。这是因为我需要将图像在页面的该部分中以不同的方式定位。
简而言之,我需要 Logo 与顶部垂直对齐,正文与左下角水平对齐。
现在,我尝试过一些事情:
- 使用
RelativeLayout
而不是Linear - 为 LinearLayout 和 ImageView 切换
gravity
和layout_gravity
,以及排除每个的组合 - 我想要的是对宽度和高度相当有信心的
match_parent
,但我尝试了与wrap_content
的不同组合
我的理解是:
gravity:top
要求父 View 使用orientation:horizontal
gravity:left
要求父 View 使用orientation:vertical
重力
适用于 View 的子级linear_gravity
应用子项与其父项对齐的方式- 在父级上使用相同的
gravity
值,在子级上使用相同的linear_gravity
值可能会产生相同的效果(当使用其中一个而不是另一个时)?
希望这是足够的信息。我很难理解这些布局的工作原理。
非常感谢您的帮助!
最佳答案
我认为您的问题是您将 ImageView 的尺寸设置为match_parent
。我会使用相对布局,因为它在您的情况下似乎是最有效的(伪 XML 代码):
RelativeLayout (width=match_parent, height=match_parent)
ImageView (width=wrap_content, height=wrap_content,
alignParentTop=true, centerHorizontal=true)
ImageView (width=wrap_content, height=wrap_content,
alignParentBottom=true, alignParentLeft=true)
这里不需要任何重力设置。您可能需要根据图像尺寸使用scaleType 属性。
关于android - 使用 XML 中的重力或 Linear_gravity 在 LinearLayout 中左对齐图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298870/