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

如何在Android Studio中创建一组仅支持单选高亮的联动按钮?

实现互斥高亮的按钮组

Button group

要实现同一时间仅高亮一个按钮的联动按钮组,这里提供两种简单可行的方案:

方案一:原生HTML+CSS实现(无需JavaScript)

利用原生单选框(radio)的互斥特性,配合CSS样式模拟按钮效果,无需编写JS逻辑:

<style>
/* 隐藏原生单选框 */
.button-group input[type="radio"] {
  display: none;
}

/* 按钮基础样式 */
.button-group label {
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
  background-color: #fff;
  transition: background-color 0.2s ease;
}

/* 选中状态的高亮样式 */
.button-group input[type="radio"]:checked + label {
  background-color: #007bff;
  color: #ffffff;
  border-color: #007bff;
}
</style>

<div class="button-group">
  <input type="radio" name="btn-group" id="btn1" checked>
  <label for="btn1">按钮一</label>
  
  <input type="radio" name="btn-group" id="btn2">
  <label for="btn2">按钮二</label>
  
  <input type="radio" name="btn-group" id="btn3">
  <label for="btn3">按钮三</label>
</div>

原理:同名的radio按钮天然互斥,点击label会触发对应radio的选中状态,通过CSS的:checked伪类为选中的按钮添加高亮样式,兼容性好且代码简洁。

方案二:JavaScript控制按钮状态

如果偏好直接使用button元素,可通过JS手动管理选中状态:

<style>
.button-group .btn {
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
  background-color: #fff;
  transition: background-color 0.2s ease;
}

.button-group .btn.active {
  background-color: #007bff;
  color: #ffffff;
  border-color: #007bff;
}
</style>

<div class="button-group">
  <button class="btn active">按钮一</button>
  <button class="btn">按钮二</button>
  <button class="btn">按钮三</button>
</div>

<script>
const buttons = document.querySelectorAll('.button-group .btn');

buttons.forEach(btn => {
  btn.addEventListener('click', () => {
    // 移除所有按钮的高亮类
    buttons.forEach(item => item.classList.remove('active'));
    // 为当前点击的按钮添加高亮类
    btn.classList.add('active');
  });
});
</script>

原理:给每个按钮绑定点击事件,点击时先清除所有按钮的高亮状态,再为当前按钮添加高亮类,实现互斥效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:48:25