Android 平铺背景正在推动它';s视图大小
我有一个平铺位图,用作Android 平铺背景正在推动它';s视图大小,android,android-layout,Android,Android Layout,我有一个平铺位图,用作视图背景。比如说,这个视图具有android:layout\u height=“wrap\u content”。问题是背景中使用的位图的高度参与了视图的测量,从而增加了视图的高度。当视图的内容大小小于用作平铺背景的位图的高度时,可以注意到这一点 让我给你举个例子。平铺位图: 位图可绘制(tile_bg.xml): 布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:androi
视图
背景。比如说,这个视图具有android:layout\u height=“wrap\u content”
。问题是背景中使用的位图的高度参与了视图的测量,从而增加了视图的高度。当视图
的内容大小小于用作平铺背景的位图的高度时,可以注意到这一点
让我给你举个例子。平铺位图:
位图可绘制(tile_bg.xml
):
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="#FFFFFF">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/tile_bg"
android:text="@string/hello"
android:textColor="#000000" />
</LinearLayout>
它看起来是什么样子:
TextView
的高度就是位图的高度。我所期望的是位图被剪裁成视图的大小
有没有办法做到这一点
注:
- 我不能使用9patch drawables,因为背景需要以瓷砖的方式重复,拉伸不是一个选项
- 我无法为
视图设置固定高度,这取决于子视图(我在视图组中使用此选项)
- 正如我之前解释的,当
视图的大小小于位图的大小时,就会发生这种奇怪的行为,否则位图会被正确地剪裁(即,如果视图大小是位图大小的1.5倍,则最终会看到位图的1.5倍)
- 该示例处理高度,但使用宽度时相同
您需要一个自定义BitmapDrawable,它从getMinimumHeight()和getMinimumWidth()返回0。下面是我命名为BitmapDrawableNoMinimumSize的一个,它完成了这项工作:
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
public class BitmapDrawableNoMinimumSize extends BitmapDrawable {
public BitmapDrawableNoMinimumSize(Resources res, int resId) {
super(res, ((BitmapDrawable)res.getDrawable(resId)).getBitmap());
}
@Override
public int getMinimumHeight() {
return 0;
}
@Override
public int getMinimumWidth() {
return 0;
}
}
当然,您不能(AFAIK)在XML中声明自定义绘图,因此您必须实例化并设置textview的背景:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BitmapDrawable bmpd =new BitmapDrawableNoMinimumSize(getResources(), R.drawable.tile);
bmpd.setTileModeX(TileMode.REPEAT);
bmpd.setTileModeY(TileMode.REPEAT);
findViewById(R.id.textView).setBackgroundDrawable(bmpd);
}
当然,您可以从布局xml中删除背景属性:
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Testing testing testing"
android:textColor="#000000" />
我已经测试过了,它似乎有效
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Testing testing testing"
android:textColor="#000000" />