安卓 ImageView:将图片放在顶部

4

我有一个只包含一个 ImageView 的活动。这个视图应该显示从 URL 加载的图像。我希望这个图片能够在顶部展示,并使用整个屏幕宽度。 我的布局文件:

<?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"
        android:background="@color/overview_bgColor" >
        <ImageView 
            android:id="@+id/overview_image"
            android:contentDescription="image"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="top|fill_horizontal"/>
    </LinearLayout>

但是图片总是垂直居中显示。为什么呢?我想,使用top应该可以将这个ImageView放在屏幕顶部吧?

1个回答

8

试试这个

<?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"
    android:background="@color/overview_bgColor" >
    <ImageView 
        android:id="@+id/overview_image"
        android:contentDescription="image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"            
     />
</LinearLayout>

这个有效,非常感谢。但是为什么 top 没有将图像视图放置在屏幕顶部? - paul_schaefer
它实际上将其放在顶部,但视图边界未设置为保留正确的比例。您可以验证一下,保留旧代码,并向ImageView添加背景,看看会发生什么,您将看到一个带有顶部和底部背景颜色的大图像。 - TootsieRockNRoll
那么确切的方法是在我的代码中添加 android:adjustViewBounds="true",还是 android:adjustViewBounds="true" 隐式地将 ImageView 放置在顶部? - paul_schaefer
adjustViewBounds 属性会根据设置为 match_parent 的图片宽度进行计算,以保持长宽比例不变。否则,会出现问题。在 Android 中,需要注意 ImageView 的使用,而它并不会将图片置于顶部。 - TootsieRockNRoll

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