什么是RadioButton、RadioContainer
RadioButton和RadioContainer是用來(lái)顯示一組單選框的,RadioButton就是單個(gè)單選框,RadioContainer就是這個(gè)組.

基礎(chǔ)樣例
1.展示一組單選框
效果圖

代碼
1). 布局文件:activity_main.xml
<RadioContainer
ohos:id="$+id:radioContainer"
ohos:height="match_content"
ohos:width="match_content">
<RadioButton
ohos:id="$+id:radioButton1"
ohos:height="match_content"
ohos:width="match_content"
ohos:marked="true"
ohos:text="我是RadioButton1"/>
<RadioButton
ohos:id="$+id:radioButton2"
ohos:height="match_content"
ohos:width="match_content"
ohos:text="我是RadioButton2"/>
</RadioContainer>
2). java代碼:
Text text = (Text) findComponentById(ResourceTable.Id_text);
RadioContainer container = (RadioContainer) findComponentById(ResourceTable.Id_radioContainer);
container.setMarkChangedListener((radioContainer, index) -> {
text.setText("當(dāng)前選中 : " + index);
});
完整代碼:
public class MainAbilitySlice extends AbilitySlice {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
Text text = (Text) findComponentById(ResourceTable.Id_text);
RadioContainer container = (RadioContainer) findComponentById(ResourceTable.Id_radioContainer);
container.setMarkChangedListener((radioContainer, index) -> {
text.setText("當(dāng)前選中 : " + index);
});
}
}
基礎(chǔ)樣例完整源代碼
https://gitee.com/hspbc/harmonyos_demos/tree/master/radioButtonDemo
常用屬性說(shuō)明
| 屬性名 | 用途 |
|---|---|
| ohos:width | 設(shè)置控件寬度,可設(shè)置為:match_parent(和父控件一樣),match_content(按照內(nèi)容自動(dòng)伸縮),設(shè)置固定值(如200vp) |
| ohos:height | 設(shè)置控件高度,可設(shè)置為:match_parent(和父控件一樣),match_content(按照內(nèi)容自動(dòng)伸縮),設(shè)置固定值(如200vp) |
| ohos:layout_alignment | 在父控件內(nèi)對(duì)齊方式,可選值:left:居左;start:居左;center:居中;right:居右;end:居右;top:居上;bottom:居下;horizontal_center:水平居中;vertical_center:垂直居中 |
| ohos:background_element | 設(shè)置背景,可以是色值(如#FF0000)或圖片等 |
| ohos:visibility | 可選值: visible(顯示), invisible(隱藏,但是仍占據(jù)UI空間),hide(隱藏,且不占UI空間) |
| ohos:text | 設(shè)置文本內(nèi)容,樣例:ohos:text="花生皮編程" |
| ohos:text_size | 設(shè)置字號(hào) |
| ohos:text_color | 設(shè)置顏色,樣例:ohos:text_color="#FF0000",ohos:text_color="red" |
| ohos:italic | 設(shè)置是否斜體,可選值:true:斜體;false:正常字體 |
| ohos:text_color_on | 設(shè)置選中時(shí),文字顏色,樣例:ohos:text_color_on="#FF0000", |
| ohos:text_color_off | 設(shè)置未選中時(shí),文字顏色,樣例:ohos:text_color_on="#00FF00", |
| ohos:marked | 設(shè)置是否選中,可選值:true:選中;false:未選中 |
更多屬性及實(shí)際效果,可以在開(kāi)發(fā)工具里自行體驗(yàn).

關(guān)于我
廈門(mén)大學(xué)計(jì)算機(jī)專(zhuān)業(yè) | 前華為工程師
專(zhuān)注分享編程技術(shù),沒(méi)啥深度,但是易懂。
Java | 安卓 | 前端 | 小程序 | 鴻蒙
公眾號(hào):花生皮編程