Android动态获取Material Color

340 阅读1分钟

我们在xml中能使用?attr/colorPrimary获取Material Design动态颜色,示例如下:

android:textColor="?attr/colorPrimary"

但是在代码中又如何获取这个动态颜色呢?找了很久终于找到了方法,示例如下:

  • 方法1
(SwipeRefreshLayout).setColorSchemeColors(MaterialColors.getColor(requireContext(),com.google.android.material.R.attr.colorPrimary,0))
(SwipeRefreshLayout).setProgressBackgroundColorSchemeColor(MaterialColors.getColor(requireContext(),com.google.android.material.R.attr.colorPrimaryContainer,0))  
  • 方法2
val typedValue = TypedValue()
theme.resolveAttribute(
    com.google.android.material.R.attr.colorPrimary,
    typedValue,
    true
)
(Button).setBackgroundColor(typedValue.data)