我有一个宽度设为fill_parent
,高度设为wrap_content
的LinearLayout
。现在我想从一个png文件中设置其背景,但传统方式会使LinearLayout
重新调整大小以显示整个背景,而不是裁剪多余部分。
如何设置LinearLayout
的背景,以使其不会重新调整大小?
谢谢
我有一个宽度设为fill_parent
,高度设为wrap_content
的LinearLayout
。现在我想从一个png文件中设置其背景,但传统方式会使LinearLayout
重新调整大小以显示整个背景,而不是裁剪多余部分。
如何设置LinearLayout
的背景,以使其不会重新调整大小?
谢谢
看起来只有使用ImageView
并相应地设置scaleType
参数才能实现这样的事情。一个快速的解决方法是使用FrameLayout
,并将ImageView
放置在具有透明背景的另一个布局下面。
代码:
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/background" />
</FrameLayout>
LinearLayout
并重写onMeasure(int,int)
回调函数来解决这个问题,然后更新布局XML以使用我的新布局类型。我不能公开那个确切的代码,但我所做的是调用super.onMeasure(int,int)
实现,并检查测量高度是否恰好等于我的背景图像的高度。如果是这样,我获取所有子视图的测量高度,然后计算一个新的高度值并将其传递给setMeasuredDimension(int,int)
。将此代码放入XML活动中,例如activity_main.xml
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="@drawable/image" />