android getResource().getColor()方法过时

本文探讨了在代码中使用ContextCompat.getColor()方法作为资源颜色获取的更佳实践,避免了直接使用带横线的资源ID,提高了代码的可读性和维护性。

可以用ContextCompat.getColor(Context context,int color)代替

毕竟代码里有条横线还是不太舒服的

你提供的这段 Kotlin 代码是用于自定义 `SmartRefreshLayout` 的刷新头部样式,继承自 `ClassicsHeader`,并设置了自定义的颜色样式。这种方式非常适合统一应用的主题风格。 --- ### ✅ 代码解析 ```kotlin class MyRefreshHeader(context: Context, attrs: AttributeSet? = null) : ClassicsHeader(context, attrs) { init { setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimaryDark)) setPrimaryColor(ContextCompat.getColor(context, R.color.colorPrimaryDark)) setAccentColor(ContextCompat.getColor(context, R.color.white)) } } ``` #### 说明: - `MyRefreshHeader` 继承自 `ClassicsHeader`,复用了其刷新动画和逻辑。 - 在 `init` 初始化块中,设置: - 背景颜色为 `colorPrimaryDark` - 主颜色也为 `colorPrimaryDark` - 强调色为白色(用于文字、进度条等) 这样可以确保刷新头部与你的 App 主题风格一致。 --- ### ✅ 使用方式回顾 在 XML 布局中引用该自定义 Header: ```xml <com.scwang.smart.refresh.layout.SmartRefreshLayout android:id="@+id/swipeRefreshLayout1_question" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@color/viewBackground"> <com.jzh.mvvm.ui.view.MyRefreshHeader android:id="@+id/ch_header_question" android:layout_width="match_parent" android:layout_height="wrap_content" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView1_question" style="@style/RecyclerViewStyle" tools:listitem="@layout/item_home_list" /> </com.scwang.smart.refresh.layout.SmartRefreshLayout> ``` --- ### ✅ 进阶建议 1. **添加自定义动画或图标**: - 如果你需要完全自定义刷新动画,可以继承 `RefreshHeader` 接口并实现动画逻辑。 2. **设置刷新文本**: - 可以通过 ` ClassicsHeader` 提供的方法修改刷新状态时的提示文字: ```kotlin this.setEnableLastTime(false) // 隐藏上次刷新时间 this.setTitleText("下拉刷新") // 自定义刷新提示文字 ``` 3. **适配深色/浅色主题切换**: - 如果你的应用支持夜间模式,可以在 `init` 中根据当前主题动态设置颜色值。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值