鸿蒙应用开发 | 单选按钮(RadioButton)和单选容器(RadioContainer)的功能与用法

885 阅读4分钟

导语:大家好,我是你们的朋友 朋哥,开发了这么久是不是发现了鸿蒙的强大之处,网上很多人说鸿蒙是Android套壳,作为一个技术人千万不要光听别人毫无根据乱说,我也劝那些说这种话的人,多了解一下。。

上一篇原创文章 使用了几种组件实现了 知乎的登录界面。也是对之前学习的组件的一种总结和实验。
今天继续我们的基础篇的开发,今天聊聊单选按钮和复选框的开发。

图片

下面我们开始今天的文章,还是老规矩,通过如下几点来说:

1,简介
2,用到的属性
3,实战
4,样式设置

简介

RadioButton是单选按钮,允许用户在一个组中选择一个选项。同一组中的单选按钮有互斥效果。

RadioButton的特点:

1.RadioButton是圆形单选框;
2.RadioContainer是个可以容纳多个RadioButton的容器;
3.在RadioContainer 中的RadioButton控件可以有多个,但同时有且仅有一个可以被选中。

4,每一个RadioButton有一个默认图标和文字组成

用到的属性

RadioButton的共有XML属性 和其它组件一样 继承自:Text

RadioButton的属性见下表:

属性很少,使用也很简单,多练练手就行哦。

实战

1,创建项目

图片

图片

2,基础的单选按钮样式

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:background_element="#999999"
    ohos:orientation="vertical">

    <RadioButton
        ohos:id="$+id:rb_1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="操作1"
        ohos:text_size="20fp"/>

    <RadioButton
        ohos:id="$+id:rb_2"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="操作2"
        ohos:text_size="20fp"/>

</DirectionalLayout>

1,创建了两个单选按钮
2,使用了默认的属性 显示文本 和默认样式 ohos:text="操作2"
效果图:

图片

样式设置

1,设置背景属性
​​​

RadioButton rb_1 = (RadioButton) findComponentById(ResourceTable.Id_rb_1);
rb_1.setButtonElement(setSelect());

初始化组件,设置背景属性。

  /**
     * 单选图片选择
     *
     * @return 单选图片选择
     */
    public StateElement setSelect() {
        StateElement stateElement = new StateElement();
        stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED},
                RadioButtonUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect));
        stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY},
                RadioButtonUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal));

        return stateElement;
    }

1,创建一个 StateElement对象,设置属性 addState 添加状态样式

2,图片设置在工具类中添加

package com.example.radiobutton.slice;

import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.*;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.util.Optional;

public class RadioButtonUtil {
    private RadioButtonUtil() {
    }
    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException | NotExistException | WrongTypeException e) {
            return path;
        }
        return path;
    }

    public static Optional<PixelMap> getPixelMap(Context context, int id) {
        String path = getPathById(context, id);
        if (path == null || path.length() <= 0) {
            return Optional.empty();
        }
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
            return Optional.empty();
        }
    }

    public static PixelMapElement getPixelMapDrawable(Context context, int resId) {
        Optional<PixelMap> optional = getPixelMap(context, resId);
        return optional.map(PixelMapElement::new).orElse(null);
    }
}

添加样式后 可以设置各种效果,所以 你直到鸿蒙的强大了把,比Android好使用多了。

效果:

图片

一个单选按钮有两种状态,选中和取消选中,各位小伙伴有没有想过 多个单选按钮怎么组合到一起的呢?下面就讲讲 RadioContainer ,这是一个RadioButton容器,用来放置多个 RadioButton。

RadioContainer的介绍和属性

RadioContainer是RadioButton的容器,在其包裹下的RadioButton保证只有一个被选项。

支持的XML属性

RadioContainer的共有XML属性继承自:DirectionalLayout

实战和使用

在layout目录下的xml文件(resources/base/layout/ability_main.xml)创建RadioContainer,并在RadioContainer中创建RadioButton。
布局样式:

<RadioContainer
        ohos:id="$+id:radio_container"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:top_margin="30vp"
        ohos:layout_alignment="horizontal_center">
        <RadioButton
            ohos:id="$+id:radio_button_1"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 1"
            ohos:text_size="14fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_2"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 2"
            ohos:text_size="14fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_3"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 3"
            ohos:text_size="14fp"/>
    </RadioContainer>

1, RadioContainer 容器中添加了三个单选按钮。
2,三个按钮只能同时选择一个。
3,ohos:orientation="horizontal" 属性设置 容器中的按钮的显示样式,分为 竖直和水平两种。

统一样式设置

RadioContainer radioContainer = (RadioContainer) findComponentById(ResourceTable.Id_radio_container);
int count = radioContainer.getChildCount();
for (int i = 0; i < count; i++){
    ((RadioButton) radioContainer.getComponentAt(i)).setButtonElement(createStateElement());
}

1,初始化容器,获取子类数量,遍历子类设置背景样式。

private StateElement createStateElement() {
    ShapeElement elementButtonOn = new ShapeElement();
    elementButtonOn.setRgbColor(RgbPalette.RED);
    elementButtonOn.setShape(ShapeElement.OVAL);

    ShapeElement elementButtonOff = new ShapeElement();
    elementButtonOff.setRgbColor(RgbPalette.WHITE);
    elementButtonOff.setShape(ShapeElement.OVAL);

    StateElement checkElement = new StateElement();
    checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn);
    checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff);
    return checkElement;
}

1,背景样式的设置,创建两个ShapeElement 一个是点击前一个是点击后。
2,设置添加状态颜色 addState

图片

完整效果

图片

完整代码:

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_parent"
    ohos:width="match_parent"
    ohos:alignment="center"
    ohos:background_element="#999999"
    ohos:orientation="vertical">

    <RadioButton
        ohos:id="$+id:rb_1"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="操作1"
        ohos:text_size="20fp"/>

    <RadioButton
        ohos:id="$+id:rb_2"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="操作2"
        ohos:text_size="20fp"/>


    <RadioContainer
        ohos:id="$+id:radio_container"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:top_margin="30vp"
        ohos:orientation="horizontal"
        ohos:layout_alignment="horizontal_center">
        <RadioButton
            ohos:id="$+id:radio_button_1"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 1"
            ohos:text_size="14fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_2"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 2"
            ohos:text_size="14fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_3"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="RadioButton 3"
            ohos:text_size="14fp"/>
    </RadioContainer>


</DirectionalLayout>

package com.example.radiobutton.slice;

import com.example.radiobutton.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentState;
import ohos.agp.components.RadioButton;
import ohos.agp.components.RadioContainer;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.element.StateElement;
import ohos.app.Context;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.util.Optional;

public class MainAbilitySlice extends AbilitySlice {
    private RadioButton rb_1;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        rb_1 = (RadioButton) findComponentById(ResourceTable.Id_rb_1);
        rb_1.setButtonElement(setSelect());
        rb_1.setClickedListener(rb_1OnClickListener);

        RadioContainer radioContainer = (RadioContainer) findComponentById(ResourceTable.Id_radio_container);
        int count = radioContainer.getChildCount();
        for (int i = 0; i < count; i++){
            ((RadioButton) radioContainer.getComponentAt(i)).setButtonElement(createStateElement());
        }
    }

    private StateElement createStateElement() {
        ShapeElement elementButtonOn = new ShapeElement();
        elementButtonOn.setRgbColor(RgbPalette.RED);
        elementButtonOn.setShape(ShapeElement.OVAL);

        ShapeElement elementButtonOff = new ShapeElement();
        elementButtonOff.setRgbColor(RgbPalette.WHITE);
        elementButtonOff.setShape(ShapeElement.OVAL);

        StateElement checkElement = new StateElement();
        checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, elementButtonOn);
        checkElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, elementButtonOff);
        return checkElement;
    }

    /**
     * 单选图片选择
     *
     * @return 单选图片选择
     */
    public StateElement setSelect() {
        StateElement stateElement = new StateElement();
        stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED},
                RadioButtonUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radioselect));
        stateElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY},
                RadioButtonUtil.getPixelMapDrawable(getContext(), ResourceTable.Media_radionormal));

        return stateElement;
    }

    private final Component.ClickedListener rb_1OnClickListener = new RadioButton.ClickedListener() {
        @Override
        public void onClick(Component component) {
            if (rb_1.isChecked()) {

            } else {

            }
        }
    };

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

老规矩 代码不能少,要不然小伙伴该说我小气了。
代码连接:gitee.com/codegrowth/…

关注公众号【程序员漫话编程】,后台回复 ”鸿蒙“即可获得上千鸿蒙开源组件。

原创不易,有用就关注一下。要是帮到了你 就给个三连吧,多谢支持。

觉得不错的小伙伴,记得帮我 点个赞和关注哟,笔芯笔芯~**

作者:码工

有问题请留言或者私信,可以 微信搜索:程序员漫话编程,关注公众号获得更多免费学习资料。