【发布时间】:2019-06-28 00:53:51
【问题描述】:
我正在寻找返回箭头的默认可绘制对象。在this question 中展示了如何在 xml 中获取它。但我正在寻找在编程方面使用(java/kotlin)。
我想在如下代码中使用这个可绘制的 id:
ContextCompat.getDrawable(context, homeAsUpIndicatorId);
【问题讨论】:
标签: java android kotlin android-resources
我正在寻找返回箭头的默认可绘制对象。在this question 中展示了如何在 xml 中获取它。但我正在寻找在编程方面使用(java/kotlin)。
我想在如下代码中使用这个可绘制的 id:
ContextCompat.getDrawable(context, homeAsUpIndicatorId);
【问题讨论】:
标签: java android kotlin android-resources
创建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>
注意:
homeAsUpIndicatorId引用的drawable 有一个 私人修饰符,所以你不能直接访问它。然而,上述 代码是从矢量 drawable 复制而来的,几乎没有修改。
我会像这样将 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()
【讨论】:
你可以用这个sn-p
val a = theme.obtainStyledAttributes(R.style.AppTheme, (R.attr.homeAsUpIndicator))
val attributeResourceId = a.getResourceId(0, 0)
val drawable = ContextCompat.getDrawable(this, attributeResourceId)
【讨论】: