2012-01-12 77 views
10

我有一个平铺的位图,我用作View背景。这个View,比方说,有android:layout_height="wrap_content"。问题是背景中使用的位图高度参与视图的测量,增加了高度。当View的内容的大小小于用作瓦片背景的位图的高度时,可以注意到这一点。平铺背景推着它的视图尺寸

让我给你看一个例子。瓷砖位图:

enter image description here

位图绘制(tile_bg.xml):

<?xml version="1.0" encoding="utf-8"?> 
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" 
    android:src="@drawable/tile" 
    android:tileMode="repeat"/> 

布局:

<?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> 

它的样子:

enter image description here

TextView的高度最终成为位图的高度。我期望的是位图被剪裁到View的大小。

有什么办法可以达到这个目的吗?

注:

  • ,因为背景需要在瓷砖时尚的方式来重复,拉伸,我不能使用9patch绘项目是不是一种选择。
  • 我不能设置一个固定的高度为View,这取决于孩子的
  • 这种奇怪的行为发生,因为我当View的大小小于之前解释(我在ViewGroup使用本)位图的大小,否则位图会被正确重复剪切(即,如果视图大小是位图大小的1.5倍,则最终会看到位图的1.5倍)。
  • 该示例处理高度,但使用宽度相同。

回答

14

您需要一个从getMinimumHeight()和getMinimumWidth()返回0的自定义BitmapDrawable。这里有一个我命名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; 
    } 
} 

当然,你不能(据我所知)在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 background属性:

<TextView 
    android:id="@+id/textView" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Testing testing testing" 
    android:textColor="#000000" /> 

我测试过这一点,它似乎工作。

+0

优秀的答案,谢谢! – aromero 2012-01-20 20:13:37