【问题标题】:ID of the back arrow drawable in the ActionBar in programming side编程端ActionBar中可绘制的后退箭头ID
【发布时间】:2019-06-28 00:53:51
【问题描述】:

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

我想在如下代码中使用这个可绘制的 id:

ContextCompat.getDrawable(context, homeAsUpIndicatorId);

【问题讨论】:

    标签: java android kotlin android-resources


    【解决方案1】:

    创建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()
    

    【讨论】:

    • 谢谢你的回答,但我需要默认的android drawable。
    • 这很好用。我真的不明白你应该否决它的原因。此外,我发布的 XML 代码是从默认矢量 drawable 复制而来的。
    • 您可以在此处找到后退按钮的原始来源:chromium.googlesource.com/android_tools/+/… 和 home 作为指示器在这里 android.googlesource.com/platform/frameworks/support/+/…
    • 默认我的意思是不添加我的drawable。
    • 检查我对帖子所做的编辑,如果这对你不起作用。那么你需要解释你真正想要什么。
    【解决方案2】:

    你可以用这个sn-p

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      相关资源
      最近更新 更多