You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android使用drawableStart时修改图标颜色无效的问题排查

问题原因及解决方案

核心原因

getCompoundDrawables()方法只能获取固定方向的Drawable(左、上、右、下,对应android:drawableLeft/drawableTop这类属性),而android:drawableStart是相对方向属性——它会根据系统的RTL/LTR布局自动调整位置,这类相对方向的Drawable不会被getCompoundDrawables()返回,所以你遍历的时候拿到的都是null。

修复方法

把代码里的btn.getCompoundDrawables()替换成btn.getCompoundDrawablesRelative(),这个方法专门用于获取相对方向的Drawable(start、top、end、bottom),能正确捕获drawableStart/drawableEnd设置的图标。

修改后的代码:

public void setColorOnButton( int id, int color){
    Button btn = findViewById( id );
    for( Drawable drawable : btn.getCompoundDrawablesRelative()) {
        if( drawable != null){
            drawable.setColorFilter(new PorterDuffColorFilter( 0xff000000|color, PorterDuff.Mode.SRC_IN));
        }
    }
}

补充说明

  • 固定方向属性(drawableLeft/drawableRight):不管布局是LTR还是RTL,图标位置固定不变
  • 相对方向属性(drawableStart/drawableEnd):会根据布局方向自动切换位置(LTR时start=left,RTL时start=right)
  • 对应获取方法:固定方向用getCompoundDrawables(),相对方向用getCompoundDrawablesRelative()

内容的提问来源于stack exchange,提问作者Style-7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 09:09:52