You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

安卓开发如何避免LinearLayout布局内的ImageView出现内容裁剪问题

问题根因

你为ImageView设置了负的顶部margin让它向上超出父布局边界,Android视图组默认开启了超出边界裁剪,所以图片上半部分被父布局剪掉。

可行解决方案

  • 给你代码里的两层LinearLayout都添加clipChildren和clipToPadding属性,关闭超出边界裁剪,修改后的XML代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="180dp"
    android:layout_height="match_parent"
    android:layout_marginHorizontal="10dp"
    android:clipChildren="false"
    android:clipToPadding="false">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/category_item_background"
        android:clickable="true"
        android:focusable="true"
        android:layout_marginTop="50dp"
        android:orientation="vertical"
        android:paddingBottom="20dp"
        android:clipChildren="false"
        android:clipToPadding="false">

        <ImageView
            android:id="@+id/planetImage"
            android:layout_marginTop="-50dp"
            android:layout_gravity="center_horizontal"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:src="@drawable/earth_transparent"
            />

        <TextView
            android:id="@+id/planetName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_marginTop="10dp"
            android:textColor="@color/white"
            android:text="Mars"
            android:fontFamily="@font/assistant_extrabold"
            android:textSize="30dp"/>

        <TextView
            android:id="@+id/planetViews"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:fontFamily="@font/assistant_extrabold"
            android:text="155 views"/>

    </LinearLayout>

</LinearLayout>
  • 可选补充:如果调整完父布局属性后,图片在ImageView内部还有拉伸裁剪的情况,可以给ImageView设置android:scaleType="fitCenter"或android:scaleType="centerInside",保证原图按比例完整展示在ImageView的100dp*100dp范围内。

内容的提问来源于stack exchange,提问作者Michal Dzurík

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 23:45:06