怎么把容器里面的按钮做成单选效果
🤖 回答引擎: 前端Lua |
🕒 时间: 2026-04-13 18:18:35 |
👁️ 阅读: 8
要在容器里实现单选按钮效果,你可以使用以下方法:
```lua
-- 假设你有一个容器布局
local container = GUI:Layout_Create(parent, "button_container", x, y, width, height)
-- 存储所有按钮和当前选中状态
local buttonList = {}
local selectedButton = nil
-- 创建按钮的函数
local function createRadioButton(index, text)
local btn = GUI:Button_Create(container, "btn_" .. index, posX, posY, "res/public/1900000612.png")
GUI:Button_setTitleText(btn, text)
-- 设置按钮默认状态
GUI:Button_loadTextureNormal(btn, "res/public/1900000612.png") -- 未选中状态
GUI:Button_loadTexturePressed(btn, "res/public/1900000612.png")
-- 添加到按钮列表
buttonList[index] = btn
-- 点击事件处理
GUI:addOnClickEvent(btn, function()
-- 如果已经选中,不做处理
if selectedButton == btn then
return
end
-- 取消之前选中的按钮
if selectedButton then
GUI:Button_loadTextureNormal(selectedButton, "res/public/1900000612.png")
end
-- 设置当前按钮为选中状态
GUI:Button_loadTextureNormal(btn, "res/public/1900000610.png") -- 选中状态使用背景图
selectedButton = btn
SL:Print("选择了按钮:", index, text)
end)
return btn
end
-- 创建多个单选按钮
for i = 1, 5 do
local posX = 100 + (i-1) * 120
local posY = 200
createRadioButton(i, "选项" .. i)
end
-- 如果需要默认选中第一个
if buttonList[1] then
GUI:addOnClickEvent(buttonList[1], function()
GUI:Button_loadTextureNormal(buttonList[1], "res/public/1900000610.png")
selectedButton = buttonList[1]
end)
-- 触发第一次点击
local clickFunc = GUI:getOnClickEvent(buttonList[1])
if clickFunc then
clickFunc()
end
end
```
**实现原理:**
1. 创建按钮时保存到`buttonList`表中
2. 点击按钮时先取消之前选中的按钮(恢复默认图片)
3. 设置当前按钮为选中状态(更换图片)
4. 用`selectedButton`变量记录当前选中的按钮
**关键点:**
- 使用不同的图片来区分选中/未选中状态
- 点击时先取消所有其他按钮的选中状态
- 只允许一个按钮被选中
这样就能在容器中实现单选按钮组的效果了。
← 返回问答库