android – 平铺的背景推动它的视图大小

我有一个平铺的位图,我正在使用作为View背景.这个视图,假设有 android:layout_height =“wrap_content”.问题是在后台使用的位图的高度参与视图的测量,增加了视图的高度.当视图的内容的大小小于用作图块背景的位图的高度时,可以注意到这一点.

让我给你一个例子.瓦片位图:

位图drawable(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>

它看起来像:

TextView的高度最终是位图的高度.我期望的是,位图被剪切到视图的大小.

有没有办法实现这一点?

笔记:

>我不能使用9patch drawables,因为背景需要以瓦片方式重复,拉伸不是一个选择.
>我不能为View设置一个固定的高度,这取决于孩子(我在ViewGroup中使用它)
>这个奇怪的行为发生在我之前解释过,当视图的大小小于位图的大小时,否则位图被重复剪辑正确(即,如果视图大小是位图的大小的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中声明自定义的drawables,所以你必须实例化并设置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" />

我已经测试了,似乎工作.

相关文章

这篇“android轻量级无侵入式管理数据库自动升级组件怎么实现...
今天小编给大家分享一下Android实现自定义圆形进度条的常用方...
这篇文章主要讲解了“Android如何解决字符对齐问题”,文中的...
这篇文章主要介绍“Android岛屿数量算法怎么使用”的相关知识...
本篇内容主要讲解“Android如何开发MQTT协议的模型及通信”,...
本文小编为大家详细介绍“Android数据压缩的方法是什么”,内...