gpt4 book ai didi

android - 背景可绘制对象定义 View 大小

转载 作者:IT老高 更新时间:2023-10-28 23:34:05 27 4
gpt4 key购买 nike

为了清楚起见,对这个问题进行了重大编辑

假设我有一个 100x100px 的 .png 资源:
enter image description here

我想将该图像用作我的 TextView 的背景,其大小由其内容决定,该内容在运行时是可变的。特别是,当 TextView 大小大于 100x100px 时,我希望该图像平铺,并且当 TextView 小于 100x100px 时,我希望它被裁剪。

后者似乎很难。

示例代码

我有一个可绘制资源bg_tile.xml:

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/bg"
android:tileMode="repeat" />

我的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:background="@drawable/bg_tile"
android:text="Short text"
android:textSize="20sp" />

<TextView android:layout_margin="8dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_tile"
android:text="Long text long text long text long text long text long text long text long text long textlong text long text long text long text long text long text long text long text long textlong text long text long text long text long text long text long text long text long text "
android:textSize="20sp" />

</LinearLayout>

发生了什么

这是这段代码的结果截图,也是我期望/我想要的结果之一: enter image description here

如您所见,平铺部分有效,底部的平铺正在被切断。但是,当 TextView 小于背景时,TextView 会占用背景的大小。

建议的解决方案

  • android:gravity="clip_vertical|clip_horizo​​ntal" - 这不起作用,即使没有 tilemode。
  • 使用 match_parent 作为布局参数 - 不是一个选项。
  • 设置一个固定的高度 - 没有办法知道 TextView 的内容会有多长,以及它的大小。

我怎样才能实现我的目标?

最佳答案

我自己没有尝试过,但你可以试试这个想法/黑客/解决方法:

View (TextView) 的最小高度/宽度由其背景可绘制对象确定(除其他外)。它使用背景 Drawable 的 getMinimumHeight() 和 getMinimumWidth() 来确定 View 的最小高度和宽度。

您似乎希望 View 的最小高度和宽度为 0(不包括填充),并且 View 的宽度/高度应仅基于 View 的内容(在您的情况下为 TextView 的文本)。

在您的 Activity 的 onCreate 或 Fragment 的 onCreateView 中尝试此操作,您可以在其中获取您尝试“修复”的 TextView。让我们将此 TextView 称为“电视”:

TextView tv; 
...
...
tv = (TextView)...findViewById(...);
....

// Swap the 'standard' bitmap background with one that has no minimum width/height.
BitmapDrawable background = (BitmapDrawable)tv.getBackground(); // assuming you have bg_tile as background.
BitmapDrawable newBackground = new BitmapDrawable(background.getBitmap) {
@Override
public int getMinimumWidth() {
return 0;
}

@Override
public int getMinimumHeight() {
return 0;
}
};
newBackground.setTileModeXY(background.getTileModeX(), background.getTileModeY());
tv.setBackgroundDrawable(newBackground);
...
...

关于android - 背景可绘制对象定义 View 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14976776/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com