java - 如何使用java代码(不是xml)在Textview中将可绘制的左图标设计为圆形(使用setCompoundDrawablesWithIntrinsicBounds添加)

标签 java android textview android-drawable

我有一个 TextView ,其图标在 TextView 中呈现。它有一个图像。我已经在文本的左侧设置了。但我需要将图标设置为圆形。
我怎样才能在java中设计这个?
enter image description here
我的代码设置在左侧。

textview.setCompoundDrawablesWithIntrinsicBounds(
                    image, 0, 0, 0);
如何为上面的 textview drawableleft 图像设计圆形图像。
 <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_vertical"
        android:ellipsize="end"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="-10dp"
        android:gravity="center"
        android:layout_marginLeft="15dp"
        android:minHeight="24dp"
        android:paddingLeft="@dimen/spacing_d2"
        android:paddingRight="@dimen/spacing_d2"
        android:tag="@string/tag_font_h_regular"
        android:fontFamily="@font/cachetbook"
        android:textColor="@color/white_new"
        android:textSize="12dp"
        tools:text="Universal Orlando Resort"/>

最佳答案

加载您的图像
您需要将图像加载为位图。如果你从你的drawable中获取if,你可以看到How to convert a Drawable to a Bitmap? .
调整大小
您可以根据需要调整位图大小以适应您的 TextView 。见 How to Resize a Bitmap in Android? .
使角变圆
根据this post您可以找到使角变圆的代码
代码示例

// Load your drawable
Drawable drawable = ContextCompat.getDrawable(this,R.drawable.ic_launcher_background);
// Convert it to a bitmap
Bitmap bitmap = Bitmap.createScaledBitmap(drawableToBitmap((drawable)),50,50,false);
// Make the corner rounded
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap);
final float roundPx = (float) bitmap.getWidth() * 90f;
roundedBitmapDrawable.setCornerRadius(roundPx);
// Apply it to the TextView
((TextView) findViewById(R.id.test)).setCompoundDrawablesWithIntrinsicBounds(
                roundedBitmapDrawable, null, null, null);
输出
enter image description here
笔记
我不知道您为什么决定选择以编程方式执行此操作,但我不会推荐它,因为它更难控制 View 和事物的定位方式。

关于java - 如何使用java代码(不是xml)在Textview中将可绘制的左图标设计为圆形(使用setCompoundDrawablesWithIntrinsicBounds添加),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64751783/

相关文章:

安卓 : programatically add id to an actionbar item

android - Kotlin - 对象表达式中的继承

java - Android - 如何用点和逗号分隔金额文本

java - 如何获取连字符第一次出现和最后一次出现之间的字符串

java - SpringXD 和 Spring Integration : Read from kafka topic every X minutes, 然后发送到另一个主题

java - 如何基于其他集合的所有元素的笛卡尔积构建集合?

java - Android GC使用什么权限

android - 在 Android 上使用 TextView 和 Html.ImageGetter 异步显示图像?

android - 具有多个项目选取框的回收站 View

java - 在设备上安装签名的 apk(使用 libgdx)时出错