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

Kotlin中如何实现二次点击OnClickListener时撤销此前的界面修改?

实现方案

你只需要新增一个布尔状态变量记录当前样式的生效状态,每次点击时根据状态执行对应样式逻辑,再翻转状态即可:

  1. 先在当前类(比如列表Adapter、Activity/Fragment)中添加成员状态变量
// 记录soul样式是否已经被激活
private var isSoulActivated = false

如果你是在列表Adapter的onBindViewHolder中设置的点击事件,需要把这个状态和对应列表项的数据绑定,不要用全局成员变量,避免列表滑动时状态错乱,比如给你的数据Bean类新增一个isSoulActivated的布尔字段即可

  1. 修改点击事件逻辑,分分支处理两种状态的样式切换:
holder.linearLayout_soul_bg.setOnClickListener {
    if (isSoulActivated) {
        // 再次点击,撤销修改,恢复为默认样式
        setBackgroundColor(/* 替换为你的默认背景色 */)
        holder.inspirationtext.setTextColor(/* 替换为你的默认文字颜色 */)
        holder.like.setImageDrawable(resources.getDrawable(/* 替换为你的默认点赞图标 */))
        holder.inspiration_title.setTextColor(/* 替换为你的默认标题颜色 */)
        holder.sourcetext.setTextColor(/* 替换为你的默认来源文字颜色 */)
        holder.sharetext.setTextColor(/* 替换为你的默认分享文字颜色 */)
        holder.sharetext.setBackgroundResource(/* 替换为你的默认分享按钮背景 */)
    } else {
        // 首次点击,应用原有修改样式
        setBackgroundColor(R.color.soul_bg)
        holder.inspirationtext.setTextColor(Color.WHITE)
        holder.like.setImageDrawable(resources.getDrawable(R.drawable.cancle_soul))
        holder.inspiration_title.setTextColor(Color.WHITE)
        holder.sourcetext.setTextColor(Color.WHITE)
        holder.sharetext.setTextColor(Color.WHITE)
        holder.sharetext.setBackgroundResource(R.drawable.small_share_bg_white)
    }
    // 翻转状态
    isSoulActivated = !isSoulActivated
}

内容的提问来源于stack exchange,提问作者Enigma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 14:45:00