HarmonyOS:利用PopupDialog实现多选效果

本文介绍了如何通过Java代码实现点击Button时,弹出包含三个选项的PopupDialog,并在用户选择RadioButton后,Button的文本随之改变,同时销毁对话框。使用了RadioContainer来组织选项,并设置了点击事件监听器来驱动功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、场景

  点击Button后弹出多个选项,用户选中其中一个选项后将选项内容显示到Button上。

二、实现效果

在这里插入图片描述

三、代码

semester = (Button) findComponentById(ResourceTable.Id_semester);
semester.setClickedListener(component -> {
    String []items = {"全部", "1", "2"};
    PopupDialog popupDialog = new PopupDialog(getContext(), component);
    RadioContainer radioContainer = new RadioContainer(getContext());
    for (int i = 0; i < 3; i++) {
        RadioButton radioButton = new RadioButton(getContext());
        radioButton.setText(items[i]);
        radioButton.setWidth(375);
        radioButton.setHeight(75);
        ShapeElement bg = new ShapeElement();
        bg.setRgbColor(RgbColor.fromArgbInt(Color.getIntColor("#85F2DC")));
        bg.setCornerRadius(30);
        radioButton.setBackground(bg);
        radioButton.setTextSize(48);
        radioButton.setTextColorOff(Color.WHITE);
        radioButton.setMarginsLeftAndRight(10, 10);
        radioButton.setMarginsTopAndBottom(10, 10);
        radioButton.setTextAlignment(TextAlignment.LEFT);
        radioButton.setClickedListener(component1 -> {   //关键代码
            semester.setText(radioButton.getText());
            popupDialog.destroy();
        });
        radioContainer.addComponent(radioButton);
    }
    radioContainer.setPadding(10, 10, 10, 10);
    popupDialog.setCustomComponent(radioContainer);   //添加组件
    popupDialog.setHasArrow(true);
    popupDialog.setArrowOffset(25);
    popupDialog.setMode(LayoutAlignment.LEFT | LayoutAlignment.BOTTOM);
    popupDialog.setBackColor(new Color(Color.getIntColor("#EEEEFF")));
    popupDialog.show();
});

  semester为Button,点击semester就弹出一个PopupDialog。由于要实现多选,所以PopupDialog的Component是一个自定义的RadioContainer,RadioContainer中包含三个选项,需要对其添加点击事件监听器:

radioButton.setClickedListener(component1 -> {
    semester.setText(radioButton.getText());
    popupDialog.destroy();
});

  当我们点击一个RadioButton时,Button会将自己的Text设置为RadioButton的Text,然后退出PopupDialog,达到选择的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cyril_KI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值