编程端 ActionBar 中可绘制的后退箭头的 ID

ID of the back arrow drawable in the ActionBar in programming side

我正在搜索后退箭头的默认可绘制对象。在 this question 中展示了如何在 xml 中获取它。但我正在寻找在编程方面使用(java/kotlin)。

我想在如下代码中使用此可绘制对象 ID:

ContextCompat.getDrawable(context, homeAsUpIndicatorId);

创建 drawable 并将 drawable id 传递给函数。例如,我创建了一个名为 arrow_back.xml 的矢量可绘制对象。

<?xml version="1.0" encoding="utf-8"?>
    <vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0"
        android:autoMirrored="true">
        <path
            android:pathData="M20,11L7.8,11l5.6,-5.6L12,4l-8,8l8,8l1.4,-1.4L7.8,13L20,13L20,11z"
            android:fillColor="#fff"/>
    </vector>

Note: the drawable that homeAsUpIndicatorId is referencing has a private modifier, so you can't access it directly. However, the above code was copied from the vector drawable with little modification.

我会像这样将 id 传递给 getDrawable() 函数。

ContextCompat.getDrawable(context, R.drawable.arrow_back);

编辑: 执行以下操作以从 homeAsUpIndicatorId 获取可绘制对象:

    TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {R.attr.homeAsUpIndicator});
    int attributeResourceId = a.getResourceId(0, 0);
    ContextCompat.getDrawable(context, attributeResourceId);
    a.recycle()

您可以使用此代码段

val a = theme.obtainStyledAttributes(R.style.AppTheme, (R.attr.homeAsUpIndicator))
val attributeResourceId = a.getResourceId(0, 0)
val drawable = ContextCompat.getDrawable(this, attributeResourceId)