如何包装内容视图而不是背景可绘制?

Pet*_*rus 20 android background

如何让LinearLayout(或任何其他ViewGroup)假设其子视图的大小而不是假设背景图像的大小?

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/large_image300x300pix">

 <TextView android:id="@+id/TextView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Hello world!"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

线性布局与背景图像的大小相同.如何让我的线性布局与textview具有相同的大小?

小智 22

好吧,所以这个帖子有点旧,但我有一个解决方案,有人可能有一天会觉得有用.我认为Android在缩小大图像方面存在问题,因此LinearLayout大小最终会被背景可绘制位图撞击,并且ImageView最终会强制增加父容器的大小.

除非你使用相对布局.即使ImageView位于父级布局的后面,也可以使ImageView相对于LinearLayout的位置.我的解决方案看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
    android:src="@drawable/activation_popup"
    android:scaleType="fitXY"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_alignTop="@+id/activation_layout"
    android:layout_alignBottom="@id/activation_layout"
    android:layout_alignLeft="@id/activation_layout"
    android:layout_alignRight="@id/activation_layout"
    android:contentDescription="@string/act_code_label" />
<LinearLayout
    android:id="@id/activation_layout"
    android:clipToPadding="true"
    android:padding="25dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <!-- LinearLayout wraps a bunch of smallish views here -->
</LinearLayout>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我在显示尺寸和操作系统版本的顶部尝试了这个,似乎工作得很好.请注意,LinearLayout中的填充是为背景图像图形中的阴影边框腾出空间的技巧.LinearLayout不需要任何相对定位,因为假设是左上角.

  • 经过数小时的搜索,这是唯一对我有用的解决方案。谢谢。 (2认同)
  • 但是,根据您对背景的意图,使用`scaleType ="centerCrop"`而不是`fitXY`可能很重要.fitXY将拉伸/缩小图像,使其与所得到的imageView的大小完全匹配,无论多高还是瘦.`centerCrop`将缩小图像,使其适合图像视图尺寸,但*会保存宽高比*,如果这对您很重要. (2认同)

Gee*_*uUp 0

如果您的图像适合转换为可扩展的 9 块图像,那么这样做会导致背景在 TextView 周围缩放。