zl程序教程

您现在的位置是:首页 >  其它

当前栏目

如何解决TextView drawableRight左侧图片大小不可控的问题

如何 解决 textview 左侧 可控 问题 图片大小
2023-09-11 14:15:13 时间

可以尝试以下两种简单方式来控制 drawableRight 图标的大小:

1,使用 TextView 的 setCompoundDrawablesRelativeWithIntrinsicBounds() 方法来设置 drawableRight 图标,并通过设置 Drawable 对象的 setBounds() 方法来控制图标大小。

Drawable drawable = ContextCompat.getDrawable(context, R.drawable.ic_icon);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2, drawable.getIntrinsicHeight() / 2);
textView.setCompoundDrawablesRelativeWithIntrinsicBounds(null, null, drawable, null);

 2.,通过在 res/drawable 目录下创建vector 矢量图,它可以无限放大或缩小而不失真,用 xml 文件来自定义 drawableRight 图标,并在 TextView 中使用该 drawable。然后在 TextView 中使用该 drawable:可以通过调整 xml 文件中的 android:width 和 android:height 属性来控制图标大小。

比如下图中的箭头图标:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:height="20dp"
        android:width="20dp"
        android:viewportHeight="1024"
        android:viewportWidth="1024">
    <path
            android:fillColor="#717171"
            android:pathData="M658.56,557.39L322.54,221.38l45.25,-45.26 336.02,336.01zM704.09,512.2L364.12,852.16l-45.26,-45.25 339.98,-339.98z"/>
</vector>

 使用:

            <TextView
                    android:id="@+id/txtShowAll"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="显示全部"
                    android:drawableRight="@drawable/ic_arow_pre_gray"
                    android:textColor="@color/SecondTextGray"/>

限制前大小:

限制后大小:

 当然箭头也可以更小: