我这里有一个xml的textView。

<TextView
        android:id="@+id/bookTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:drawableLeft="@drawable/checkmark"
        android:gravity="center_vertical"
        android:textStyle="bold"
        android:textSize="24dip"
        android:maxLines="1"
        android:ellipsize="end"/>

正如你所看到的,我在xml中设置了drawablleft。

我想在代码中改变可绘制的。

有办法做这件事吗?或者在文本视图的代码中设置drawablleft ?


当前回答

一个Kotlin扩展+一些填充周围的可绘制

fun TextView.addLeftDrawable(drawable: Int, padding: Int = 32) {
    val imgDrawable = ContextCompat.getDrawable(context, drawable)
    compoundDrawablePadding = padding
    setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}

其他回答

一个Kotlin扩展+一些填充周围的可绘制

fun TextView.addLeftDrawable(drawable: Int, padding: Int = 32) {
    val imgDrawable = ContextCompat.getDrawable(context, drawable)
    compoundDrawablePadding = padding
    setCompoundDrawablesWithIntrinsicBounds(imgDrawable, null, null, null)
}

从这里我看到方法setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)可以用来做到这一点。

有两种方法可以使用XML或Java。 如果它是静态的,不需要更改,那么可以在XML中初始化。

  android:drawableLeft="@drawable/cloud_up"
    android:drawablePadding="5sp"

现在如果你需要动态地改变图标,那么你可以通过 根据事件调用图标

       textViewContext.setText("File Uploaded");
textViewContext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uploaded, 0, 0, 0);
static private Drawable **scaleDrawable**(Drawable drawable, int width, int height) {

    int wi = drawable.getIntrinsicWidth();
    int hi = drawable.getIntrinsicHeight();
    int dimDiff = Math.abs(wi - width) - Math.abs(hi - height);
    float scale = (dimDiff > 0) ? width / (float)wi : height /
            (float)hi;
    Rect bounds = new Rect(0, 0, (int)(scale * wi), (int)(scale * hi));
    drawable.setBounds(bounds);
    return drawable;
}

我这样用。

  txtUserName.setCompoundDrawablesWithIntrinsicBounds(
        requireActivity().getDrawable(
            R.drawable.ic_my_account
        ), null, null, null
    )