如何将 TextInputLayout startIcon 设置为具有多个路径的 VectorDrawable

How to set TextInputLayout startIcon to VectorDrawable with multiple paths

我无法将 Android Material TextInputLayout startIcon 设置为具有多个路径的 VectorDrawable

这是 VectorDrawableXML

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24">
    <path
        android:fillColor="#FFF"
        android:pathData="M12,12m-10,0a10,10 0,1 1,20 0a10,10 0,1 1,-20 0" />
    <path
        android:fillColor="#000"
        android:pathData="M11,13H13V15H11M11,9H13V11H11M11,17H13A2,2 0 0,0 15,15V13.5A1.5,1.5 0 0,0 13.5,12A1.5,1.5 0 0,0 15,10.5V9A2,2 0 0,0 13,7H11A2,2 0 0,0 9,9V10.5A1.5,1.5 0 0,0 10.5,12A1.5,1.5 0 0,0 9,13.5V15A2,2 0 0,0 11,17M12,1C5.92,1 1,5.92 1,12C1,18.08 5.92,23 12,23C18.08,23 23,18.08 23,12C23,5.92 18.08,1 12,1M12,19A7,7 0 0,1 5,12A7,7 0 0,1 12,5A7,7 0 0,1 19,12A7,7 0 0,1 12,19Z" />
</vector>

它在 Android Studio 预览中看起来像一个 8 球,但加载时它只是一个灰色圆圈。

我试过用两个单独的 VectorDrawable 制作一个 LayerList,以编程方式加载图像并通过 XML,但是 none 成功了。图像可以很好地加载到 ImageView 中。感谢我能得到的任何帮助。

您可以通过使用 TextInputLayout 的开始图标可绘制资源标识符以编程方式设置它来解决此问题,即 text_input_start_icon.

要获取资源整数 ID,请使用:资源 class.

getIdentifer()
val startIconViewId = resources.getIdentifier(
    "text_input_start_icon", "id",
    packageName
)
val textInputLayout = findViewById<TextInputLayout>(R.id.my_text_input_layout)
val startIconDrawable: CheckableImageButton = textInputLayout.findViewById(startIconViewId)

val view = View(this)
view.setBackgroundResource(R.drawable.my_vector_drawable)
startIconDrawable.setBackground(view.background)

但您还必须在 xml 布局中保持 app:startIconDrawable 设置。

Do you know how to change the size? Changing the XML height and width isn't working. Also, having the startIconDrawable set in XML is causing both icons to appear on my device.

您可以更改 CheckableImageButton 本身的高度和宽度。

val layoutParams = startIconDrawable.layoutParams
layoutParams.height = 100
layoutParams.width = 100
startIconDrawable.setBackground(view.background)

结果: