如何为SwipeRefreshLayout组件添加Material You动态色彩?
解决SwipeRefreshLayout使用Material You动态色彩修改刷新箭头颜色的问题
实现步骤
- 先确保你的App主题已启用Material You动态色彩,比如使用
Theme.Material3.DynamicColors.DayNight作为父主题,或者在主题配置中设置dynamicColor="true"。 - 在Kotlin代码中获取动态色彩并设置给SwipeRefreshLayout:
方法一:通过主题属性获取动态主色调
方法二:直接使用Material库提供的动态颜色资源val swipeRefresh = findViewById<SwipeRefreshLayout>(R.id.your_swipe_refresh_id) // 从主题中解析动态主色调 val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.colorPrimary, typedValue, true) val dynamicPrimaryColor = typedValue.data swipeRefresh.setColorSchemeColors(dynamicPrimaryColor)val swipeRefresh = findViewById<SwipeRefreshLayout>(R.id.your_swipe_refresh_id) val dynamicPrimaryColor = ContextCompat.getColor(this, com.google.android.material.R.color.material_dynamic_primary) swipeRefresh.setColorSchemeColors(dynamicPrimaryColor)
补充说明
启用动态色彩后,主题中的colorPrimary会自动适配用户壁纸生成的主色调,所以通过主题属性获取的颜色就是Material You的动态色彩。如果需要其他动态色调(比如secondary、tertiary),可以替换对应的属性或资源ID,比如android.R.attr.colorSecondary或com.google.android.material.R.color.material_dynamic_secondary。
内容的提问来源于stack exchange,提问作者dem
相关产品推荐
相关产品推荐

