为什么上下文不具有活动的主要颜色属性?

我正在写一个图书馆,有一个照片编辑活动。 当用户完成编辑时,会出现一个带有彩色背景的“完成”按钮。 我想能够自定义按钮的颜色,所以我有不同的类中创建不同颜色的drawable的静态方法。 我想在这个类中做的事情是一个函数,它接收一个Context引用,并用原色创建一个drawable。 这是我的代码:

 //code from FlatButtonDrawable class companion object fun new(ctx: Context): StateListDrawable{ val typedValue = TypedValue(); val a = ctx.obtainStyledAttributes(typedValue.data, intArrayOf(R.attr.colorPrimary)) val color = a.getColor(0, 0); a.recycle(); return createColorDrawable(color) } 

这个函数从Context获取主要的颜色,并返回一个可绘制的颜色。 问题是找不到primaryColor属性,所以它返回一个无色的drawable。

更奇怪的是,如果我在我的活动中获取主要颜色, 然后调用静态方法,它就可以工作。 代码如下:

 //code from activity class val sendButton = findViewById(R.id.sendPhoto) as Button val typedValue = TypedValue(); val a = obtainStyledAttributes(typedValue.data, intArrayOf(R.attr.colorPrimary)) val color = a.getColor(0,0) a.recycle() sendButton.background =FlatButtonDrawable.createColorDrawable(color) 

所以真正的问题是: 为什么使用活动的上下文引用从我的静态方法调用obtainStyledAttributes失败,但从活动调用时成功?