文章目录

喜欢记得点个赞哟,我是王睿,很高兴认识大家!

1、Text【文本框】

1.1、Text 是什么?

简单:文本框组件
官方:Text是用来显示字符串的组件,在界面上显示为一块文本区域。

1.2、点击时:自动调节字体大小+动态增加文字

Harmony OS 组件篇_Harmony OS 常用组件
MainAbilitySlice.java

Text text = (Text) findComponentById(ResourceTable.Id_text);
// 设置自动调整规则
text.setAutoFontSizeRule(30, 100, 1);
// 设置点击一次增多一个"T"
text.setClickedListener(new Component.ClickedListener() {
    @Override
    public void onClick(Component component) {
        text.setText(text.getText() + "T");
    }
});

ability_main.xml

<DependentLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_content">
    <Text
        ohos:id="$+id:text"
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:text="TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText"
        ohos:text_size="50fp"
        ohos:text_color="#0000FF"
        ohos:italic="true"
        ohos:text_alignment="vertical_center"
        ohos:text_weight="700"
        ohos:text_font="serif"
        ohos:background_element="$graphic:background_text"/>
</DependentLayout>

1.3、跑马灯效果

Harmony OS 组件篇_王睿丶_02

MainAbilitySlice.java

        Text text = (Text) findComponentById(ResourceTable.Id_text);
// 跑马灯效果
        text.setTruncationMode(Text.TruncationMode.AUTO_SCROLLING);
// 始终处于自动滚动状态
        text.setAutoScrollingCount(Text.AUTO_SCROLLING_FOREVER);
// 启动跑马灯效果
        text.startAutoScrolling();

ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DependentLayoHut
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_content"
    ohos:background_element="$graphic:color_light_gray_element">
    <Text
        ohos:id="$+id:text"
        ohos:width="75vp"
        ohos:height="match_content"
        ohos:text="TextText"
        ohos:text_size="28fp"
        ohos:text_color="#0000FF"
        ohos:italic="true"
        ohos:text_alignment="vertical_center"
        ohos:text_weight="700"
        ohos:text_font="serif"
        ohos:background_element="$graphic:background_text"/>
</DependentLayoHut>

1.4、实战:一个标题栏和详细内容的界面

Harmony OS 组件篇_Harmony OS_03

ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DependentLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_content"
    ohos:background_element="$graphic:color_light_gray_element">
    <Text
        ohos:id="$+id:text1"
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:text_size="25fp"
        ohos:top_margin="15vp"
        ohos:left_margin="15vp"
        ohos:right_margin="15vp"
        ohos:background_element="$graphic:background_text"
        ohos:text="Title"
        ohos:text_weight="1000"
        ohos:text_alignment="horizontal_center"/>
    <Text
        ohos:id="$+id:text2"
        ohos:width="match_parent"
        ohos:height="120vp"
        ohos:text_size="25fp"
        ohos:background_element="$graphic:background_text"
        ohos:text="Content"
        ohos:top_margin="15vp"
        ohos:left_margin="15vp"
        ohos:right_margin="15vp"
        ohos:bottom_margin="15vp"
        ohos:text_alignment="center"
        ohos:below="$id:text1"
        ohos:text_font="serif"/>
    <Button
        ohos:id="$+id:button1"
        ohos:width="75vp"
        ohos:height="match_content"
        ohos:text_size="15fp"
        ohos:background_element="$graphic:background_text"
        ohos:text="Previous"
        ohos:right_margin="15vp"
        ohos:bottom_margin="15vp"
        ohos:left_padding="5vp"
        ohos:right_padding="5vp"
        ohos:below="$id:text2"
        ohos:left_of="$id:button2"
        ohos:text_font="serif"/>
    <Button
        ohos:id="$+id:button2"
        ohos:width="75vp"
        ohos:height="match_content"
        ohos:text_size="15fp"
        ohos:background_element="$graphic:background_text"
        ohos:text="Next"
        ohos:right_margin="15vp"
        ohos:bottom_margin="15vp"
        ohos:left_padding="5vp"
        ohos:right_padding="5vp"
        ohos:align_parent_end="true"
        ohos:below="$id:text2"
        ohos:text_font="serif"/>
</DependentLayout>

下面这两个是自定义样式文件,需要放在 resources/base/graphic目录下,新建background_text.xml 与 color_light_gray_element.xml文件

background_text.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners
        ohos:radius="20"/>
    <solid
        ohos:color="#878787"/>
</shape>

color_light_gray_element.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <solid
        ohos:color="#EDEDED"/>
</shape>

Text更多详情

2、Button【按钮】

2.1、Button 是什么?

简单:按钮组件
官方:Button是一种常见的组件,点击可以触发对应的操作,通常由文本或图标组成,也可以由图标和文本共同组成。

2.2、普通按钮

Harmony OS 组件篇_Harmony OS 常用组件_04

<Button
    ohos:width="150vp"
    ohos:height="50vp"
    ohos:text_size="27fp"
    ohos:text="button"
    ohos:background_element="$graphic:color_blue_element"
    ohos:left_margin="15vp"
    ohos:bottom_margin="15vp"
    ohos:right_padding="8vp"
    ohos:left_padding="8vp"
/>

color_blue_element.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <solid
        ohos:color="#007CFD"/>
</shape>

2.3、椭圆按钮

Harmony OS 组件篇_移动开发_05

<Button
    ohos:width="150vp"
    ohos:height="50vp"
    ohos:text_size="27fp"
    ohos:text="button"
    ohos:background_element="$graphic:oval_button_element"
    ohos:left_margin="15vp"
    ohos:bottom_margin="15vp"
    ohos:right_padding="8vp"
    ohos:left_padding="8vp"
    ohos:element_left="$media:ic_btn_reload"
/>

oval_button_element.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="oval">
    <solid
        ohos:color="#007CFD"/>
</shape>

2.4、实战:拨号盘的UI界面

Harmony OS 组件篇_王睿丶_06

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:background_element="$graphic:color_light_gray_element"
    ohos:orientation="vertical">
    <Text
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:text_size="20fp"
        ohos:text="0123456789"
        ohos:background_element="$graphic:green_text_element"
        ohos:text_alignment="center"
        ohos:layout_alignment="horizontal_center"
    />
    <DirectionalLayout
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:alignment="horizontal_center"
        ohos:orientation="horizontal"
        ohos:top_margin="5vp"
        ohos:bottom_margin="5vp">
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="1"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="2"
            ohos:left_margin="5vp"
            ohos:right_margin="5vp"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="3"
            ohos:text_alignment="center"
        />
    </DirectionalLayout>
    <DirectionalLayout
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:alignment="horizontal_center"
        ohos:orientation="horizontal"
        ohos:bottom_margin="5vp">
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="4"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:left_margin="5vp"
            ohos:right_margin="5vp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="5"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="6"
            ohos:text_alignment="center"
        />
    </DirectionalLayout>
    <DirectionalLayout
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:alignment="horizontal_center"
        ohos:orientation="horizontal"
        ohos:bottom_margin="5vp">
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="7"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:left_margin="5vp"
            ohos:right_margin="5vp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="8"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="9"
            ohos:text_alignment="center"
        />
    </DirectionalLayout>
    <DirectionalLayout
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:alignment="horizontal_center"
        ohos:orientation="horizontal"
        ohos:bottom_margin="5vp">
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="*"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:left_margin="5vp"
            ohos:right_margin="5vp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="0"
            ohos:text_alignment="center"
        />
        <Button
            ohos:width="40vp"
            ohos:height="40vp"
            ohos:text_size="15fp"
            ohos:background_element="$graphic:green_circle_button_element"
            ohos:text="#"
            ohos:text_alignment="center"
        />
    </DirectionalLayout>
    <Button
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:text_size="15fp"
        ohos:text="CALL"
        ohos:background_element="$graphic:green_capsule_button_element"
        ohos:bottom_margin="5vp"
        ohos:text_alignment="center"
        ohos:layout_alignment="horizontal_center"
        ohos:left_padding="10vp"
        ohos:right_padding="10vp"
        ohos:top_padding="2vp"
        ohos:bottom_padding="2vp"
    />
</DirectionalLayout>

color_light_gray_element.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <solid
        ohos:color="#EDEDED"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners
        ohos:radius="20"/>
    <stroke
        ohos:width="2"
        ohos:color="#006E00"/>
    <solid
        ohos:color="#EDEDED"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="oval">
    <stroke
        ohos:width="5"
        ohos:color="#006E00"/>
    <solid
        ohos:color="#EDEDED"/>
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:shape="rectangle">
    <corners
        ohos:radius="100"/>
    <solid
        ohos:color="#006E00"/>
</shape>

Button 更多详情

3、TextField【输入框】

3.1、TextField 是什么?

简单:文本输入框组件
官方:TextField 提供了一种文本输入框组件。

3.2、创建文本框、设置基线、设置气泡

Harmony OS 组件篇_应用层开发_07
ability_main.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">
    <TextField
    ohos:id="$+id:text_field"
    ohos:height="40vp"
    ohos:width="200vp"
    ohos:background_element="$graphic:background_text_field"
    ohos:left_padding="20vp"
    ohos:hint="Enter phone number or email"
    ohos:layout_alignment="horizontal_center"
    ohos:top_margin="60fp"
    ohos:element_cursor_bubble="$graphic:ele_cursor_bubble"
    ohos:basement="#000099"
    ohos:text_alignment="vertical_center"/>
</DirectionalLayout>

background_text_field.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="40"/>
    <solid
        ohos:color="#FFFFFF"/>
</shape>

ele_cursor_bubble.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="40"/>
    <solid
        ohos:color="#6699FF"/>
    <stroke
        ohos:color="#0066FF"
        ohos:width="10"/>
</shape>

3.3、实战:点击登录按钮,将会出现提示用户名错误,同时将会改变TextField的状态

Harmony OS 组件篇_Harmony OS 常用组件_08

MainAbilitySlice.java

 		
 			// 当点击登录,改变相应组件的样式
        Button button = (Button) findComponentById(ResourceTable.Id_ensure_button);
        button.setClickedListener((component -> {
        
            Text text = (Text) findComponentById(ResourceTable.Id_error_tip_text);
            //  显示错误提示的Text
            text.setVisibility(Component.VISIBLE);

            TextField textField = (TextField) findComponentById(ResourceTable.Id_name_textField);
            // 显示TextField错误状态下的样式
            ShapeElement errorElement = new ShapeElement(this, ResourceTable.Graphic_background_text_field_error);
            textField.setBackground(errorElement);

            // TextField失去焦点
            textField.clearFocus();
        }));
            

ability_main.xml

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

    <StackLayout
        ohos:top_margin="60vp"
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:layout_alignment="center">
        <TextField
            ohos:id="$+id:name_textField"
            ohos:width="match_parent"
            ohos:height="match_content"
            ohos:multiple_lines="false"
            ohos:left_padding="24vp"
            ohos:right_padding="24vp"
            ohos:top_padding="8vp"
            ohos:bottom_padding="8vp"
            ohos:min_height="44vp"
            ohos:text_size="18fp"
            ohos:layout_alignment="center"
            ohos:text_alignment="vertical_center"
            ohos:background_element="$graphic:background_text_field"
            ohos:hint="Enter phone number or email" />

        <Text
            ohos:visibility="hide"
            ohos:id="$+id:error_tip_text"
            ohos:width="match_content"
            ohos:height="match_content"
            ohos:top_padding="8vp"
            ohos:bottom_padding="8vp"
            ohos:right_margin="20vp"
            ohos:text="Incorrect account or password"
            ohos:text_size="18fp"
            ohos:text_color="red"
            ohos:layout_alignment="right"/>
    </StackLayout>

    <TextField
        ohos:top_margin="40vp"
        ohos:id="$+id:password_text_field"
        ohos:width="match_parent"
        ohos:height="match_content"
        ohos:multiple_lines="false"
        ohos:left_padding="24vp"
        ohos:right_padding="24vp"
        ohos:top_padding="8vp"
        ohos:bottom_padding="8vp"
        ohos:min_height="44vp"
        ohos:text_size="18fp"
        ohos:layout_alignment="center"
        ohos:text_alignment="vertical_center"
        ohos:background_element="$graphic:background_text_field"
        ohos:hint="Enter password" />

    <Button
        ohos:top_margin="40vp"
        ohos:id="$+id:ensure_button"
        ohos:width="120vp"
        ohos:height="35vp"
        ohos:background_element="$graphic:background_btn"
        ohos:text="Log in"
        ohos:text_size="20fp"
        ohos:layout_alignment="horizontal_center"/>

</DirectionalLayout>

background_text_field.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="40"/>
    <solid
        ohos:color="white"/>
    <stroke
        ohos:color="black"
        ohos:width="6"/>
</shape>

background_btn.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="35"/>
    <solid
        ohos:color="white"/>
</shape>

3.4、常用属性(xml 和 Java)

xml属性

background_element		背景样式
hint					提示文字
element_cursor_bubble	气泡
multiple_lines			多行显示
basement				设置基线(底边线)

java

TextField textField = (TextField) findComponentById(ResourceTable.Id_text_field);

//获取输入框的内容
String content = textField.getText();

//设置TextField不可用状态
textField.setEnabled(false);

//响应焦点变化
textField.setFocusChangedListener((component, isFocused) -> {
    
    if (isFocused) { 
        // 获取到焦点
        ...
    } else { 
        // 失去焦点
        ...
    }
});

TextField 更多详情

4、Image【图片】

4.1、Image 是什么?

Image是用来显示图片的组件

4.2、创建Image的两种方式:

(1)准备工作 将图片放入 resources/media/

Harmony OS 组件篇_移动开发_09
Harmony OS 组件篇_王睿丶_10

(2)方式一:在XML中创建Image

   <Image
        ohos:id="$+id:image"
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:layout_alignment="center"
        ohos:image_src="$media:haixing"/>

(3)方式二:在Java代码中创建Image

//创建Image 对象
Image image = new Image(getContext());
//设置图片(参数:资源路径)
image.setPixelMap(ResourceTable.Media_plant);

4.3、常用属性

(1)设置透明度效果
Harmony OS 组件篇_王睿丶_11

ohos:image_src="$media:plant"		

(2)设置缩放系数
Harmony OS 组件篇_移动开发_12

    ohos:scale_x="0.5"
    ohos:scale_y="0.5"

(3)设置缩放方式
Harmony OS 组件篇_Harmony OS 常用组件_13

ohos:scale_mode="zoom_center"

(4)设置剪切对齐方式
Harmony OS 组件篇_王睿丶_14

ohos:clip_alignment="left"

Image更多详情

5、TabList和Tab【分页栏】

5.1、TabList 是什么?

简单:页签栏组件
官方:Tablist可以实现多个页签栏的切换,Tab为某个页签。子页签通常放在内容区上方,展示不同的分类。页签名称应该简洁明了,清晰描述分类的内容。

5.2、TabList 常用属性

(1)设置默认状态和选中状态的字体颜色和indicator的颜色

<TabList
    ...
    ohos:normal_text_color="#999999"
    ohos:selected_text_color="#FFFFFF"
    ohos:selected_tab_indicator_color="#FFFFFF"
    ohos:selected_tab_indicator_height="2vp"/>

(2)设置Tab的布局

tabList.setTabLength(140 * 3); // 设置Tab的宽度
tabList.setTabMargin(24 * 3); // 设置两个Tab之间的间距

(3)设置固定模式
默认为false,该模式下TabList的总宽度是各Tab宽度的总和,若固定了TabList的宽度,当超出可视区域,则可以通过滑动TabList来显示。如果设置为true,TabList的总宽度将与可视区域相同,各个Tab的宽度也会根据TabList的宽度而平均分配,该模式适用于Tab较少的情况。

tabList.setFixedMode(true);

Harmony OS 组件篇_移动开发_15

tabList.setFixedMode(false);

Harmony OS 组件篇_王睿丶_16

(4)在某个位置新增Tab

TabList.Tab tab = tabList.new Tab(getContext());
tab.setText("News");
tab.setMinWidth(64);
tab.setPadding(12, 0, 12, 0);
tabList.addTab(tab, 1); // 1表示位置

(5)响应焦点变化

tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
    @Override
    public void onSelected(TabList.Tab tab) {
        // 当某个Tab从未选中状态变为选中状态时的回调
        ...
    }

    @Override
    public void onUnselected(TabList.Tab tab) {
        // 当某个Tab从选中状态变为未选中状态时的回调
        ...
    }

    @Override
    public void onReselected(TabList.Tab tab) {
        // 当某个Tab已处于选中状态,再次被点击时的状态回调
        ...
    }
});

5.3、Tab 常用属性

(1)设置Tab属性

tab.setMinWidth(64);
tab.setPadding(12, 0, 12, 0);

(2)选中某个Tab

tab.select();

(3)获取Tab在TabList中的位置索引

tab.getPosition();

5.4、实战:三个页签栏切换

Harmony OS 组件篇_移动开发_17

MainAbilitySlice.java

        TabList tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
        tabList.setTabLength(140*3);    // 设置Tab的宽度
        tabList.setTabMargin(24*3);     // 设置两个Tab之间的间距

        //添加标签
        TabList.Tab tab1 = tabList.new Tab(getContext());
        tab1.setText("Image");
        tabList.addTab(tab1);

        TabList.Tab tab2 = tabList.new Tab(getContext());
        tab2.setText("Video");
        tabList.addTab(tab2);

        TabList.Tab tab3= tabList.new Tab(getContext());
        tab3.setText("Audio");
        tabList.addTab(tab3);
     
        tabList.setFixedMode(true);		//设置固定模式

ability_main.xml

<?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:background_element="black"
    ohos:orientation="vertical">

    <TabList
        ohos:id="$+id:tab_list"
        ohos:top_margin="40vp"
        ohos:tab_margin="24vp"
        ohos:tab_length="140vp"
        ohos:text_size="20fp"
        ohos:height="36vp"
        ohos:width="match_parent"
        ohos:layout_alignment="center"
        ohos:orientation="horizontal"
        ohos:text_alignment="center"
        ohos:normal_text_color="#999999"
        ohos:selected_text_color="#FFFFFF"
        ohos:selected_tab_indicator_color="#FFFFFF"
        ohos:selected_tab_indicator_height="2vp"/>

</DirectionalLayout>

TabList和Tab 更多详情

6、Picker【滑动选择器】

6.1、Picker 是什么?

Picker提供了滑动选择器,允许用户从预定义范围中进行选择。

6.2、简单实现

Harmony OS 组件篇_应用层开发_18

  • 在XML中创建Picker
<Picker
    ohos:id="$+id:test_picker"
    ohos:height="match_content"
    ohos:width="300vp"
    ohos:background_element="#E1FFFF"
    ohos:layout_alignment="horizontal_center"
    ohos:normal_text_size="16fp"
    ohos:selected_text_size="16fp"/>
  • 设置Picker的取值范围
Picker picker = (Picker) findComponentById(ResourceTable.Id_test_picker);
picker.setMinValue(0); // 设置选择器中的最小值
picker.setMaxValue(6); // 设置选择器中的最大值

6.3、实战1:简单样式

  • 响应选择器变化
picker.setValueChangedListener((picker1, oldVal, newVal) -> {
    // oldVal:上一次选择的值; newVal:最新选择的值
});
  • 格式化Picker的显示
    通过Picker的setFormatter(Formatter formatter)方法,用户可以将Picker选项中显示的字符串修改为特定的格式。
    Harmony OS 组件篇_移动开发_19
picker.setFormatter(i -> {
    String value;
    switch (i) {
        case 0:
            value = "Mon";
            break;
        case 1:
            value = "Tue";
            break;
        case 2:
            value = "Wed";
            break;
        case 3:
            value = "Thu";
            break;
        case 4:
            value = "Fri";
            break;
        case 5:
            value = "Sat";
            break;
        case 6:
            value = "Sun";
            break;
        default:
            value = "" + i;
    }
    return value;
});
  • 设置要显示的字符串数组
    对于不直接显示数字的组件,该方法可以设置字符串与数字一一对应。字符串数组长度必须等于取值范围内的值总数。用户在使用时需要注意,该方法会覆盖picker.setFormatter(Formatter formatter)方法。
picker.setDisplayedData(new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"});

6.4、实战2:更多样式

(1)设置文本样式

Harmony OS 组件篇_Harmony OS_20

<?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:background_element="black"
    ohos:orientation="vertical">

    <Picker
        ohos:id="$+id:test_picker"
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:background_element="#E1FFFF"
        ohos:layout_alignment="horizontal_center"
        ohos:normal_text_size="16fp"
        ohos:normal_text_color="#FFA500"
        ohos:selected_text_size="16fp"
        ohos:selected_text_color="#00FFFF"
        />

</DirectionalLayout>
 Picker picker = (Picker) findComponentById(ResourceTable.Id_test_picker);
        picker.setDisplayedData(new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"});

//设置文本样式
picker.setNormalTextFont(Font.DEFAULT_BOLD);
picker.setNormalTextSize(40);
picker.setNormalTextColor(new Color(Color.getIntColor("#FFA500")));
picker.setSelectedTextFont(Font.DEFAULT_BOLD);
picker.setSelectedTextSize(40);
picker.setSelectedTextColor(new Color(Color.getIntColor("#00FFFF")));

(2) 设置所选文本的上下边框

Harmony OS 组件篇_移动开发_21

<Picker
    ...
    ohos:bottom_line_element="#40E0D0"
    ohos:top_line_element="#40E0D0"/>
//创建 shape 对象
ShapeElement shape = new ShapeElement();
//设置矩形
shape.setShape(ShapeElement.RECTANGLE);
//设置颜色
shape.setRgbColor(RgbColor.fromArgbInt(0xFF40E0D0));
// 单独设置上边框
// picker.setDisplayedLinesTopElement(shape); 
// 单独设置下边框
// picker.setDisplayedLinesBottomElement(shape);
// 同时设置上下边框
picker.setDisplayedLinesElements(shape, shape);

(3)设置Picker的着色器颜色

Harmony OS 组件篇_Harmony OS_22

<Picker
    ...
    ohos:shader_color="#1E90FF"/>
picker.setShaderColor(new Color(Color.getIntColor("#1E90FF")));

(4)设置Picker中所选文本边距与普通文本边距的比例

Harmony OS 组件篇_王睿丶_23

<Picker
    ...
    ohos:selected_normal_text_margin_ratio="5.0">
</Picker>
picker.setSelectedNormalTextMarginRatio(5.0f);

(5)设置选择轮模式
该模式是来决定Picker是否是循环显示数据的。

Harmony OS 组件篇_Harmony OS 常用组件_24

<Picker
    ...
    ohos:wheel_mode_enabled="true"/>
picker.setWheelModeEnabled(true);

Picker 更多详情

7、DatePicker【日期选择器】

7.1、DatePicker 是什么?

日期选择器

7.2、简单实现

Harmony OS 组件篇_Harmony OS 常用组件_25

    <DatePicker
        ohos:id="$+id:date_pick"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:text_size="20vp"
        ohos:background_element="#FF98C6F1">
    </DatePicker>

7.3、实战事件

(1)响应日期改变事件:

Harmony OS 组件篇_Harmony OS 常用组件_26

  • 在XML中添加Text显示选择日期:
<Text
    ohos:id="$+id:text_date"
    ohos:height="match_content"
    ohos:width="match_parent"
    ohos:hint="date"
    ohos:margin="8vp"
    ohos:padding="4vp"
    ohos:text_size="14fp">
</Text>
  • 在Java代码中响应日期改变事件:
DatePicker datePicker = (DatePicker) findComponentById(ResourceTable.Id_date_pick);
Text selectedDate = (Text) findComponentById(ResourceTable.Id_text_date);
datePicker.setValueChangedListener(
        new DatePicker.ValueChangedListener() {
            @Override		//参数依次为:实例、年、月、日
            public void onValueChanged(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                selectedDate.setText(String.format("%02d/%02d/%4d", dayOfMonth, monthOfYear, year));
            }
        }
);
  • 获取当前选择日期,日/月/年,DatePicker默认选择当前日期。
DatePicker datePicker = (DatePicker) findComponentById(ResourceTable.Id_date_pick);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();

7.4、常用属性

(1)设置当前日期

datePicker.updateDate(2021, 8, 8);

(2)设置日期的范围
如需对DatePicker的日期选择范围有要求,可以设置属性min_date和max_date。设置的值为日期对应的Unix时间戳

  • 设置最小日期
<DatePicker
    ...
    ohos:min_date="1627747200">
</DatePicker>
datePicker.setMinDate(1627747200);
  • 设置最大日期
<DatePicker
    ...
    ohos:max_date="1630339200">
</DatePicker>
datePicker.setMaxDate(1630339200);

(3)固定年/月/日
xml与java选任意一种既可

<DatePicker
    ...
    ohos:year_fixed="true">
</DatePicker>
datePicker.setYearFixed(true);

7.5、实战样式

(1)设置待选项的字体大小和颜色效果
Harmony OS 组件篇_Harmony OS_27

<DatePicker
    ...
    ohos:normal_text_color="#00FFFF"
    ohos:normal_text_size="20fp">
</DatePicker>

(2)设置已选项的字体大小和颜色
Harmony OS 组件篇_移动开发_28

<DatePicker
    ...
    ohos:selected_text_color="#00FFFF"
    ohos:selected_text_size="20fp">
</DatePicker>
datePicker.setSelectedTextSize(40);
datePicker.setSelectedTextColor(new Color(Color.getIntColor("#FFA500")));

(3)设置操作项的字体颜色

Harmony OS 组件篇_移动开发_29

<DatePicker
    ...
    ohos:operated_text_color="#00FFFF">
</DatePicker>
datePicker.setOperatedTextColor(new Color(Color.getIntColor("#00FFFF")));

(4)设置DatePicker中所选文本边距与普通文本边距的比例

Harmony OS 组件篇_应用层开发_30

<DatePicker
    ...
    ohos:selected_normal_text_margin_ratio="10">
</DatePicker>
datePicker.setSelectedNormalTextMarginRatio(10.0f)

(5)设置滚轮绕行(数据循环)

Harmony OS 组件篇_移动开发_31

<DatePicker
    ...
    ohos:wheel_mode_enabled="true">
</DatePicker>
datePicker.setWheelModeEnabled(true);

(6)设置选中日期的上下边框

Harmony OS 组件篇_Harmony OS 常用组件_32

<DatePicker
    ...
    ohos:top_line_element="#9370DB"
    ohos:bottom_line_element="#9370DB">
</DatePicker>
ShapeElement shape = new ShapeElement();
shape.setShape(ShapeElement.RECTANGLE);
shape.setRgbColor(RgbColor.fromArgbInt(0xFF9370DB));
datePicker.setDisplayedLinesElements(shape,shape);

(7)设置着色器颜色
Harmony OS 组件篇_Harmony OS_33

<DatePicker
    ...
    ohos:shader_color="gray">
</DatePicker>
datePicker.setShaderColor(new Color(Color.getIntColor("#00CED1")));

DatePicker 了解更多

8、TimePicker【时间选择器】

8.1、TimePicker 是什么?

时间选择器

8.2、简单实现

Harmony OS 组件篇_Harmony OS_34

    <TimePicker
        ohos:id="$+id:time_picker"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:normal_text_size="18fp"
        ohos:selected_text_size="26fp"/>

8.3、实战:显示样式

(1)设置字体属性

  • a. 设置未选中字体的颜色和大小
    Harmony OS 组件篇_应用层开发_35
<TimePicker
    ...
    ohos:normal_text_color="#007DFF"
    ohos:normal_text_size="20fp"
/>
  • b. 设置选中字体的颜色和大小
    Harmony OS 组件篇_王睿丶_36
<TimePicker
    ...
    ohos:selected_text_color="#007DFF"
    ohos:selected_text_size="20fp"
/>
  • c. 设置选中字体的颜色和大小效果

Harmony OS 组件篇_应用层开发_37

<TimePicker
    ...
    ohos:operated_text_color="#FF9912"
/>

(2)设置TimePicker中所选文本边距与普通文本边距的比例
Harmony OS 组件篇_应用层开发_38

<TimePicker
    ...
    ohos:selected_normal_text_margin_ratio="10"
/>

(3)设置着色器颜色
Harmony OS 组件篇_移动开发_39

<TimePicker
    ...
    ohos:shader_color="#00BFFF"
/>

(4)设置选中时间的上下边框
Harmony OS 组件篇_Harmony OS_40

<TimePicker
    ...
    ohos:bottom_line_element="#00BFFF"
/>

(5)设置12小时制下显示样式
AM/PM默认置于左侧,如需位于右边:
Harmony OS 组件篇_移动开发_41

<TimePicker
    ...
    ohos:am_pm_order="1"
/>

8.4、常用属性

获取时间

TimePicker timePicker = (TimePicker) findComponentById(ResourceTable.Id_time_picker);
int hour = timePicker.getHour();
int minute = timePicker.getMinute();
int second = timePicker.getSecond();

设置时间

timePicker.setHour(19);
timePicker.setMinute(18);
timePicker.setSecond(12);

响应时间改变事件

timePicker.setTimeChangedListener(new TimePicker.TimeChangedListener() {
    @Override
    public void onTimeChanged(TimePicker timePicker, int hour, int minute, int second) {
        ...
    }
});

范围选择设置及更多详情

9、Switch【开关状态】

9.1、Switch 是什么?

简单:状态组件
官方:Switch是切换单个设置开/关两种状态的组件

9.2、简单使用

Harmony OS 组件篇_应用层开发_42

    <Switch
        ohos:id="$+id:btn_switch"
        ohos:height="60vp"
        ohos:width="100vp"
        ohos:top_margin="50fp"
        ohos:layout_alignment="center"
        ohos:text_state_off="OFF"
        ohos:text_state_on="ON"
        />

9.3、常用属性

(1)设置Switch在开启和关闭时的文本

Harmony OS 组件篇_移动开发_43

<Switch
    ...
    ohos:text_state_off="OFF"
    ohos:text_state_on="ON"/>
Switch btnSwitch = (Switch) findComponentById(ResourceTable.Id_btn_switch);
btnSwitch.setStateOffText("OFF");
btnSwitch.setStateOnText("ON");

(2)设置响应Switch状态改变的事件

btnSwitch.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
    // 回调处理Switch状态改变事件
    @Override
    public void onCheckedChanged(AbsButton button, boolean isChecked) {

    }
});

9.4、实战:自定义Switch

Harmony OS 组件篇_Harmony OS_44

    <Switch
        ohos:id="$+id:btn_switch"
        ohos:height="60vp"
        ohos:width="100vp"
        ohos:top_margin="50fp"
        ohos:layout_alignment="center"
        ohos:text_state_off="OFF"
        ohos:text_state_on="ON"
        />
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);


        //创建shape实例,并设置样式
        // 开启状态下滑块的样式
        ShapeElement elementThumbOn = new ShapeElement();
        elementThumbOn.setShape(ShapeElement.OVAL);
        elementThumbOn.setRgbColor(RgbColor.fromArgbInt(0xFF1E90FF));
        elementThumbOn.setCornerRadius(50);

        // 关闭状态下滑块的样式
        ShapeElement elementThumbOff = new ShapeElement();
        elementThumbOff.setShape(ShapeElement.OVAL);
        elementThumbOff.setRgbColor(RgbColor.fromArgbInt(0xFFFFFFFF));
        elementThumbOff.setCornerRadius(50);

        // 开启状态下轨迹样式
        ShapeElement elementTrackOn = new ShapeElement();
        elementTrackOn.setShape(ShapeElement.RECTANGLE);
        elementTrackOn.setRgbColor(RgbColor.fromArgbInt(0xFF87CEFA));
        elementTrackOn.setCornerRadius(50);
        // 关闭状态下轨迹样式
        ShapeElement elementTrackOff = new ShapeElement();
        elementTrackOff.setShape(ShapeElement.RECTANGLE);
        elementTrackOff.setRgbColor(RgbColor.fromArgbInt(0xFF808080));
        elementTrackOff.setCornerRadius(50);
        
        Switch btnSwitch = (Switch) findComponentById(ResourceTable.Id_btn_switch);
        btnSwitch.setTrackElement(trackElementInit(elementTrackOn, elementTrackOff));
        btnSwitch.setThumbElement(thumbElementInit(elementThumbOn, elementThumbOff));
    }

	//设置轨迹样式
    private StateElement trackElementInit(ShapeElement on, ShapeElement off){
        StateElement trackElement = new StateElement();
        trackElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, on);
        trackElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, off);
        return trackElement;
    }

	//设置滑块样式
    private StateElement thumbElementInit(ShapeElement on, ShapeElement off) {
        StateElement thumbElement = new StateElement();
        thumbElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, on);
        thumbElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, off);
        return thumbElement;
    }

Switch 了解更多

10、RadioButton【单选按钮】

10.1、RadioButton 是什么?

简单:单选按钮
官方:RadioButton用于多选一的操作,需要搭配RadioContainer使用,实现单选效果。

10.2、简单使用

Harmony OS 组件篇_移动开发_45

    <RadioButton
        ohos:id="$+id:rb_1"
        ohos:height="40vp"
        ohos:width="match_content"
        ohos:text="A.Learning"
        ohos:margin="30fp"
        ohos:text_size="20fp"/>

10.3、设置 RadioButton 样式

Harmony OS 组件篇_应用层开发_46

<RadioButton
    ...
    ohos:text_color_on="#00BFFF"
    ohos:text_color_off="#808080"/>
rBtn.setTextColorOn(new Color(Color.getIntColor("#0066FF")));
rBtn.setTextColorOff(new Color(Color.getIntColor("#505050")));

了解更多

11、RadioContainer【单选按钮组】

11.1、RadioContainer 是什么?

简单:单选按钮租
官方:RadioContainer是RadioButton的容器,在其包裹下的RadioButton保证只有一个被选项。

11.2、简单使用

Harmony OS 组件篇_Harmony OS 常用组件_47

    <RadioContainer
        ohos:id="$+id:radio_container"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:top_margin="32vp"
        ohos:layout_alignment="horizontal_center">
        <RadioButton
            ohos:id="$+id:radio_button_1"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="A.Learning"
            ohos:text_color_on="#00BFFF"
            ohos:text_color_off="#808080"
            ohos:text_size="20fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_2"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text_color_on="#00BFFF"
            ohos:text_color_off="#808080"
            ohos:text="A.Innovation"
            ohos:text_size="20fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_3"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text_color_on="#00BFFF"
            ohos:text_color_off="#808080"
            ohos:text="A.Benefit"
            ohos:text_size="20fp"/>
        <RadioButton
            ohos:id="$+id:radio_button_4"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="A.Unity"
            ohos:text_color_on="#00BFFF"
            ohos:text_color_off="#808080"
            ohos:text_size="20fp"/>
    </RadioContainer>

11.3、常用属性

(1)设置响应RadioContainer状态改变的事件

RadioContainer container = (RadioContainer) findComponentById(ResourceTable.Id_radio_container);
container.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
    @Override
    public void onCheckedChanged(RadioContainer radioContainer, int index) {
    // 可参考下方场景实例代码,自行实现
    ...
    }
});

(2)根据索引值设置指定RadioButton为选定状态

container.mark(0);

(3)清除RadioContainer中所有RadioButton的选定状态

container.cancelMarks();

(4)设置RadioButton的布局方向:orientation设置为“horizontal”,表示横向布局;orientation设置为“vertical”,表示纵向布局。默认为纵向布局。

Harmony OS 组件篇_Harmony OS 常用组件_48

<RadioContainer
    ...
    ohos:orientation="horizontal">
    ...
</RadioContainer>
container.setOrientation(Component.HORIZONTAL);

11.4、实战:实现单选题的选择效果

Harmony OS 组件篇_Harmony OS 常用组件_49

        RadioContainer radioContainer = (RadioContainer) findComponentById(ResourceTable.Id_radio_container);
        int count = radioContainer.getChildCount();
        //给每个RadioButton 设置背景
        for (int i = 0; i < count; i++){
            ((RadioButton) radioContainer.getComponentAt(i)).setButtonElement(createStateElement());
        }

        Text answer = (Text) findComponentById(ResourceTable.Id_text_checked);
        radioContainer.setMarkChangedListener((radioContainer1, index) -> {
            //参数一:格式符,参数二:ASCLL码值 + 坐标 = 选择的值
            answer.setText(String.format("[%c]",(char)('A'+index)));
        });

<?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="horizontal_center"
    ohos:orientation="vertical"
    ohos:left_padding="32vp">
    <Text
        ohos:height="match_content"
        ohos:width="300vp"
        ohos:top_margin="32vp"
        ohos:text="Question:Which of the following options belong to fruit?"
        ohos:text_size="20fp"
        ohos:layout_alignment="left"
        ohos:multiple_lines="true"/>
    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal"
        ohos:top_margin="8vp">
        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text="Your Answer:"
            ohos:text_size="20fp"/>
        <Text
            ohos:id="$+id:text_checked"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text_size="20fp"
            ohos:left_margin="18vp"
            ohos:text="[]"
            ohos:text_color="#FF3333"/>
    </DirectionalLayout>
    <RadioContainer
        ohos:id="$+id:radio_container"
        ohos:height="match_content"
        ohos:width="200vp"
        ohos:layout_alignment="left"
        ohos:orientation="vertical"
        ohos:top_margin="16vp"
        ohos:left_margin="4vp">
        <RadioButton
            ohos:id="$+id:radio_button_1"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="A.Apple"
            ohos:text_size="20fp"
            ohos:text_color_on="#FF3333"/>
        <RadioButton
            ohos:id="$+id:radio_button_2"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="B.Potato"
            ohos:text_size="20fp"
            ohos:text_color_on="#FF3333"/>
        <RadioButton
            ohos:id="$+id:radio_button_3"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="C.Pumpkin"
            ohos:text_size="20fp"
            ohos:text_color_on="#FF3333"/>
        <RadioButton
            ohos:id="$+id:radio_button_4"
            ohos:height="40vp"
            ohos:width="match_content"
            ohos:text="D.Vegetables"
            ohos:text_size="20fp"
            ohos:text_color_on="#FF3333"/>
    </RadioContainer>
</DirectionalLayout>

了解更多

12、Checkbox【多选框】

12.1、Checkbox 是什么?

简单:多选框
官方:可以实现选中和取消选中的功能。

12.2、简单实现

Harmony OS 组件篇_Harmony OS_50

<Checkbox
    ohos:id="$+id:check_box"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:text="This is a checkbox"
    ohos:text_size="20fp" />

12.3、设置 Checkbox

(1)配置Checkbox的选中和取消选中的状态标志样式
Harmony OS 组件篇_Harmony OS 常用组件_51

<Checkbox
    ...
    ohos:check_element="$graphic:checkbox_check_element" />
  • graphic目录下创建checkbox_check_element.xml、background_checkbox_checked.xml和background_checkbox_empty.xml三个文件。

  • checkbox_check_element.xml

<?xml version="1.0" encoding="utf-8"?>
<state-container xmlns:ohos="http://schemas.huawei.com/res/ohos">
    <item ohos:state="component_state_checked" ohos:element="$graphic:background_checkbox_checked"/>
    <item ohos:state="component_state_empty" ohos:element="$graphic:background_checkbox_empty"/>
</state-container>
  • background_checkbox_checked.xml
<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <solid
        ohos:color="#00BFC9"/>
</shape>

background_checkbox_empty.xml

<?xml version="1.0" encoding="UTF-8" ?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <solid
        ohos:color="#000000"/>
</shape>

(2)设置Checkbox文字颜色的效果
Harmony OS 组件篇_王睿丶_52

  • 设置Checkbox的文字在选中和取消选中时的颜色
<Checkbox
    ...
    ohos:text_color_on="#00AAEE"
    ohos:text_color_off="#000000" />

(3)设置Checkbox的选中状态

checkbox.setChecked(true);

(4)设置不同状态之间的切换:如果当前为选中状态,那么将变为未选中;如果当前是未选中状态,将变为选中状态

checkbox.toggle();

(5) 设置响应Checkbox状态变更的事件

// state表示是否被选中
checkbox.setCheckedStateChangedListener((component, state) -> {
    // 状态改变的逻辑
    ...
});

12.4、实战:实现多选题的选择效果

Harmony OS 组件篇_Harmony OS 常用组件_53

public class MainAbilitySlice extends AbilitySlice {
    // 保存最终选中的结果
    private Set<String> selectedSet = new HashSet<>();

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initCheckbox();
    }

    // 初始化Checkbox
    private void initCheckbox() {
        Checkbox checkbox1 = (Checkbox) findComponentById(ResourceTable.Id_check_box_1);
        checkbox1.setButtonElement(elementButtonInit());
        checkbox1.setCheckedStateChangedListener((component, state) -> {
            if (state) {
                selectedSet.add("A");
            } else {
                selectedSet.remove("A");
            }
            showAnswer();
        });
        Checkbox checkbox2 = (Checkbox) findComponentById(ResourceTable.Id_check_box_2);
        checkbox2.setButtonElement(elementButtonInit());
        checkbox2.setCheckedStateChangedListener((component, state) -> {
            if (state) {
                selectedSet.add("B");
            } else {
                selectedSet.remove("B");
            }
            showAnswer();
        });
        Checkbox checkbox3 = (Checkbox) findComponentById(ResourceTable.Id_check_box_3);
        checkbox3.setButtonElement(elementButtonInit());
        checkbox3.setCheckedStateChangedListener((component, state) -> {
            if (state) {
                selectedSet.add("C");
            } else {
                selectedSet.remove("C");
            }
            showAnswer();
        });
        Checkbox checkbox4 = (Checkbox) findComponentById(ResourceTable.Id_check_box_4);
        checkbox4.setButtonElement(elementButtonInit());
        checkbox4.setCheckedStateChangedListener((component, state) -> {
            if (state) {
                selectedSet.add("D");
            } else {
                selectedSet.remove("D");
            }
            showAnswer();
        });
    }

    // 设置Checkbox背景
    private StateElement elementButtonInit() {
        ShapeElement elementButtonOn = new ShapeElement();
        elementButtonOn.setRgbColor(RgbPalette.RED);
        elementButtonOn.setShape(ShapeElement.OVAL);

        ShapeElement elementButtonOff = new ShapeElement();
        elementButtonOff.setRgbColor(RgbPalette.BLACK);
        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;
    }

    // 显示结果
    private void showAnswer() {
        Text answerText = (Text) findComponentById(ResourceTable.Id_text_answer);
        String answer = selectedSet.toString();
        answerText.setText(answer);
    }
}
<?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:orientation="vertical"
    ohos:left_padding="40vp"
    ohos:top_padding="40vp">

    <DirectionalLayout
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:orientation="horizontal">

        <Text
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:text_size="18fp"
            ohos:text="Which of the following are fruits?"/>

        <Text
            ohos:id="$+id:text_answer"
            ohos:height="match_content"
            ohos:width="match_content"
            ohos:left_margin="20vp"
            ohos:text_size="20fp"
            ohos:text_color="#FF3333"
            ohos:text="[]" />
    </DirectionalLayout>

    <Checkbox
        ohos:id="$+id:check_box_1"
        ohos:top_margin="40vp"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="A Apples"
        ohos:text_size="20fp"
        ohos:text_color_on="#FF3333"
        ohos:text_color_off="#000000"/>

    <Checkbox
        ohos:id="$+id:check_box_2"
        ohos:top_margin="40vp"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="B Bananas"
        ohos:text_size="20fp"
        ohos:text_color_on="#FF3333"
        ohos:text_color_off="#000000"/>

    <Checkbox
        ohos:id="$+id:check_box_3"
        ohos:top_margin="40vp"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="C Strawberries"
        ohos:text_size="20fp"
        ohos:text_color_on="#FF3333"
        ohos:text_color_off="#000000" />

    <Checkbox
        ohos:id="$+id:check_box_4"
        ohos:top_margin="40vp"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:text="D Potatoes"
        ohos:text_size="20fp"
        ohos:text_color_on="#FF3333"
        ohos:text_color_off="black" />
</DirectionalLayout>

12.5、了解更多

Checkbox 了解更多

13、ProgressBar【垂直、水平进度条】

13.1、ProgressBar 是什么?

简单:水平或垂直进度条
官方:ProgressBar用于显示内容或操作的进度。

13.2、简单使用

Harmony OS 组件篇_Harmony OS_54

   <ProgressBar
        ohos:progress_width="10vp"
        ohos:height="60vp"
        ohos:width="200fp"
        ohos:max="100"
        ohos:min="0"
        ohos:progress="60"/>

13.3、设置 ProgressBar

(1)设置ProgressBar方向为垂直
Harmony OS 组件篇_应用层开发_55

    <ProgressBar
        ohos:progress_width="10vp"
        ohos:height="150vp"
        ohos:width="200fp"
        ohos:max="100"
        ohos:orientation="vertical"
        ohos:min="0"
        ohos:progress="60"/>

(2)设置当前进度

<ProgressBar
    ...
    ohos:progress="60"/>
progressBar.setProgressValue(60);

(3)设置最大和最小值
Harmony OS 组件篇_Harmony OS 常用组件_56

<ProgressBar
    ...
    ohos:max="400"
    ohos:min="0"/>
progressBar.setMaxValue(400);
progressBar.setMinValue(0);

(4)设置ProgressBar进度颜色

<ProgressBar
    ...
    ohos:progress_element="#FF9900" />

Harmony OS 组件篇_Harmony OS_57

(5)设置底色颜色效果

<ProgressBar
    ...
    ohos:background_instruct_element="#FFFFFF" />

(6)设置ProgressBar分割线

Harmony OS 组件篇_王睿丶_58

<ProgressBar
    ...
    ohos:divider_lines_enabled="true"
    ohos:divider_lines_number="5" />
progressBar.enableDividerLines(true);
progressBar.setDividerLinesNumber(5);

(7)设置ProgressBar分割线颜色
Harmony OS 组件篇_移动开发_59

progressBar.setDividerLineColor(Color.MAGENTA);

(8)设置ProgressBar提示文字
Harmony OS 组件篇_Harmony OS 常用组件_60

<ProgressBar
    ...
    ohos:progress_hint_text="20%"
    ohos:progress_hint_text_color="#FFCC99" />

13.4、了解更多

ProgressBar 了解更多

14、RoundProgressBar【圆形进度条】

14.1、RoundProgressBar 是什么?

简单:圆形进度条
官方:RoundProgressBar继承自ProgressBar,拥有ProgressBar的属性,在设置同样的属性时用法和ProgressBar一致,用于显示环形进度。

14.2、简单使用

Harmony OS 组件篇_Harmony OS_61

    <RoundProgressBar
        ohos:id="$+id:round_progress_bar"
        ohos:height="200vp"
        ohos:width="200vp"
        ohos:progress_width="10vp"
        ohos:progress="20"
        ohos:progress_color="#47CC47"/>

14.3、设置 RoundProgressBar样式

Harmony OS 组件篇_移动开发_62

    <RoundProgressBar
        ohos:id="$+id:round_progress_bar"
        ohos:height="200vp"
        ohos:width="200vp"
        ohos:progress_width="10vp"
        ohos:start_angle="45"
        ohos:max_angle="270"
        ohos:progress="20"
        ohos:progress_hint_text="Round"
        ohos:progress_hint_text_color="#007DFF"
        ohos:progress_color="#47CC47"/>

14.4、了解更多

RoundProgressBar 更多

15、ToastDialog【提示对话框】

15.1、ToastDialog 是什么?

简单:提示对话框
官方:ToastDialog是在窗口上方弹出的对话框,是通知操作的简单反馈。ToastDialog会在一段时间后消失,在此期间,用户还可以操作当前窗口的其他组件。

15.2、简单实用

Harmony OS 组件篇_Harmony OS_63

 Button button = (Button) findComponentById(ResourceTable.Id_btn_dianwo);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
            //创建一个ToastDialog
                new ToastDialog(getContext())
                        .setText("This is a ToastDialog")
                        .show();
            }
        });
    <Button
        ohos:id="$+id:btn_dianwo"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:layout_alignment="center"
        ohos:text="点我"
        ohos:margin="40fp"
        ohos:text_size="25fp"
        ohos:background_element="#FF53C3DE"/>

15.3、设置 ToastDialog

(1)设置位置

new ToastDialog(getContext())
    .setText("This is a ToastDialog displayed in the middle")
    .setAlignment(LayoutAlignment.CENTER)
    .show();

15.4、自定义ToastDialog的Component

Harmony OS 组件篇_Harmony OS_64

新建:layout_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:orientation="vertical">
    <Text
        ohos:id="$+id:msg_toast"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_padding="16vp"
        ohos:right_padding="16vp"
        ohos:top_padding="4vp"
        ohos:bottom_padding="4vp"
        ohos:layout_alignment="center"
        ohos:text_size="16fp"
        ohos:text="This is a ToastDialog for the customized component"
        ohos:background_element="$graphic:background_toast_element"/>
</DirectionalLayout>    

background_toast_element.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="30vp"/>
    <solid
        ohos:color="#66808080"/>
</shape>
Button button = (Button) findComponentById(ResourceTable.Id_btn_dianwo);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
            //自定义ToastDialog的Component
                DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(MainAbilitySlice.this)
                        .parse(ResourceTable.Layout_layout_toast, null, false);
                new ToastDialog(getContext())
                        .setContentCustomComponent(toastLayout)
                        .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                        .setAlignment(LayoutAlignment.CENTER)
                        .show();
            }
        });

15.5、实战:自定义添加多个视图的场景

Harmony OS 组件篇_Harmony OS_65

新建:layout_toast_and_image.xml

<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:orientation="horizontal">

    <Image
        ohos:width="30vp"
        ohos:height="30vp"
        ohos:scale_mode="inside"
        ohos:image_src="$media:icon"/>

    <Text
        ohos:id="$+id:msg_toast"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:background_element="$graphic:background_toast_element"
        ohos:bottom_padding="4vp"
        ohos:layout_alignment="vertical_center"
        ohos:left_padding="16vp"
        ohos:right_padding="16vp"
        ohos:text="This is a ToastDialog with An Image"
        ohos:text_size="16fp"
        ohos:top_padding="4vp"/>
</DirectionalLayout>

background_toast_element.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="30vp"/>
    <solid
        ohos:color="#66808080"/>
</shape>
        Button button = (Button) findComponentById(ResourceTable.Id_btn_dianwo);
        button.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                DirectionalLayout layout = (DirectionalLayout) LayoutScatter.getInstance(MainAbilitySlice.this)
                        .parse(ResourceTable.Layout_layout_toast_and_image, null, false);
                new ToastDialog(getContext())
                        .setContentCustomComponent(layout)
                        .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                        .setAlignment(LayoutAlignment.CENTER)
                        .show();
            }
        });

15.6、更多

ToastDialog 更多

16、ScrollView【滑动视图】

16.1、ScrollView 是什么?

简单:滑动视图
官方:ScrollView是一种带滚动功能的组件,它采用滑动的方式在有限的区域内显示更多的内容。

16.2、简单实用

Harmony OS 组件篇_移动开发_66

 <ScrollView
        ohos:id="$+id:scrollview"
        ohos:height="300vp"
        ohos:width="300vp"
        ohos:background_element="#FFDEAD"
        ohos:top_margin="32vp"
        ohos:bottom_padding="16vp"
        ohos:layout_alignment="horizontal_center">
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_content">
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:Android"/>
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:AI"/>
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:AIOT"/>

            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:HarmonyOS"/>

        </DirectionalLayout>
    </ScrollView>

16.3、设置 ScrollView

Harmony OS 组件篇_Harmony OS 常用组件_67

(1)点击按钮,根据像素数平滑滚动。

       ScrollView scrollView = (ScrollView) findComponentById(ResourceTable.Id_scrollview);
        Button btnScroll= (Button) findComponentById(ResourceTable.Id_btnScroll);
        //根据像素数平滑滚动
        btnScroll.setClickedListener(component -> {
            scrollView.fluentScrollByY(300);
        });
<?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:orientation="vertical"
    ohos:left_padding="40vp"
    ohos:top_padding="40vp">

    <ScrollView
        ohos:id="$+id:scrollview"
        ohos:height="300vp"
        ohos:width="300vp"
        ohos:background_element="#FFDEAD"
        ohos:top_margin="32vp"
        ohos:bottom_padding="16vp"
        ohos:layout_alignment="horizontal_center">
        <DirectionalLayout
            ohos:height="match_content"
            ohos:width="match_content">
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:Android"/>
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:AI"/>
            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:AIOT"/>

            <Image
                ohos:width="300vp"
                ohos:height="match_content"
                ohos:top_margin="16vp"
                ohos:image_src="$media:HarmonyOS"/>

        </DirectionalLayout>
    </ScrollView>

    <Button
        ohos:id="$+id:btnScroll"
        ohos:height="match_content"
        ohos:width="match_parent"
        ohos:background_element="#FFF10B0B"
        ohos:text_size="20vp"
        ohos:text_color="#FFFAF6F6"
        ohos:top_margin="15fp"
        ohos:text="Scroll By Y:300"/>

</DirectionalLayout>

(2)点击按钮,平滑滚动到指定位置
Harmony OS 组件篇_应用层开发_68

scrollView.fluentScrollYTo(500);

(3)设置水平方向
Harmony OS 组件篇_应用层开发_69

<ScrollView
    ...
    ohos:rebound_effect="true">
        ...
</ScrollView>

(4)设置回弹效果

Harmony OS 组件篇_应用层开发_70

<ScrollView
    ...
    ohos:rebound_effect="true">
        ...
</ScrollView>
scrollView.setReboundEffect(true);

(5)设置缩放匹配效果

<ScrollView
    ...
    ohos:match_viewport="true">
        ...
</ScrollView>
scrollView.setMatchViewportEnabled(true);

16.4、了解更多

ScrollView 更多

17、ListContainer【列表】

17.1、ListContainer 是什么?

简单:列表
官方:ListContainer是用来呈现连续、多行数据的组件,包含一系列相同类型的列表项。

17.2、简单使用

Harmony OS 组件篇_应用层开发_71

  • ability_main.xml
<?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:orientation="vertical"
    ohos:left_padding="40vp"
    ohos:top_padding="40vp">

    <ListContainer
        ohos:id="$+id:list_container"
        ohos:height="200vp"
        ohos:width="300vp"
        ohos:layout_alignment="horizontal_center"/>

</DirectionalLayout>
  • 在layout目录下新建xml文件(例:item_sample.xml),作为ListContainer的子布局。
<?xml version="1.0" encoding="utf-8"?>
<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:height="match_content"
    ohos:width="match_parent"
    ohos:left_margin="16vp"
    ohos:right_margin="16vp"
    ohos:orientation="vertical">
    <Text
        ohos:id="$+id:item_index"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:padding="4vp"
        ohos:text="Item0"
        ohos:text_size="20fp"
        ohos:layout_alignment="center"/>
</DirectionalLayout>
  • 创建SampleItem.java,作为ListContainer的数据包装类。
public class SampleItem {
    private String name;
    public SampleItem(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
  • ListContainer每一行可以为不同的数据,因此需要适配不同的数据结构,使其都能添加到ListContainer上。
    创建SampleItemProvider.java,继承自BaseItemProvider。必须重写的方法如下:
    Harmony OS 组件篇_Harmony OS_72
    代码示例如下:
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import java.util.List;
public class SampleItemProvider extends BaseItemProvider {
    private List<SampleItem> list;
    private AbilitySlice slice;
    public SampleItemProvider(List<SampleItem> list, AbilitySlice slice) {
        this.list = list;
        this.slice = slice;
    }
    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }
    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()){
            return list.get(position);
        }
        return null;
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_item_sample, null, false);
        } else { 
            cpt = convertComponent;
        }
        SampleItem sampleItem = list.get(position);
        Text text = (Text) cpt.findComponentById(ResourceTable.Id_item_index);
        text.setText(sampleItem.getName());
        return cpt;
    }
}
  • 在Java代码中添加ListContainer的数据,并适配其数据结构
public class MainAbilitySlice extends AbilitySlice {

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initListContainer();
    }

    //初始化数据
    private void initListContainer() {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        List<SampleItem> list = getData();
        SampleItemProvider sampleItemProvider = new SampleItemProvider(list, this);
        listContainer.setItemProvider(sampleItemProvider);
    }
    private ArrayList<SampleItem> getData() {
        ArrayList<SampleItem> list = new ArrayList<>();
        for (int i = 0; i <= 30; i++) {
            list.add(new SampleItem("Item" + i));
        }
        return list;
    }

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

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

17.3、ListContainer 常用接口

(1)设置响应点击事件
Harmony OS 组件篇_Harmony OS_73

listContainer.setItemClickedListener((container, component, position, id) -> {
    SampleItem item = (SampleItem) listContainer.getItemProvider().getItem(position);
    new ToastDialog(this)
            .setText("you clicked:" + item.getName())
            // Toast显示在界面中间
            .setAlignment(LayoutAlignment.CENTER)
            .show();
});

(2)设置响应长按事件

listContainer.setItemLongClickedListener((container, component, position, id) -> {
    SampleItem item = (SampleItem) listContainer.getItemProvider().getItem(position);
    new ToastDialog(this)
            .setText("you long clicked:" + item.getName())
            .setAlignment(LayoutAlignment.CENTER)
            .show();
     return false;
});

17.4、ListContainer 样式设置

ListContainer的样式设置相关的接口如下:
Harmony OS 组件篇_应用层开发_74

(1)设置水平布局

Harmony OS 组件篇_Harmony OS_75

<ListContainer
    ...
    ohos:orientation="horizontal"/>
listContainer.setOrientation(Component.HORIZONTAL);

(2)自定义样式
实现:在子布局和ListContainer布局中添加背景色

Harmony OS 组件篇_Harmony OS 常用组件_76

  • 设置ListContainer的开始和结束偏移量
listContainer.setContentOffSet(32, 16);
  • 在item_sample.xml的根布局中添加背景色
<DirectionalLayout
    ...
    ohos:background_element="#FAEBD7">
    ...
</DirectionalLayout>
  • 在ListContainer布局文件中添加背景色
<ListContainer
    ...
    ohos:background_element="#FFDEAD"/>

(3)设置回弹效果

Harmony OS 组件篇_应用层开发_77

<ListContainer
    ...
    ohos:rebound_effect="true"/>
listContainer.setReboundEffect(true);
  • 在开启回弹效果后,可以调用setReboundEffectParams()方法调整回弹效果。
listContainer.setReboundEffectParams(40, 0.6f, 20);

(4)设置着色器颜色
Harmony OS 组件篇_王睿丶_78

<ListContainer
    ...
    ohos:shader_color="#90EE90"/>
listContainer.setShaderColor(new Color(Color.getIntColor("#90EE90")));

17.5、ListContainer 性能优化

Harmony OS 组件篇_Harmony OS 常用组件_79

17.6、更多

ListContainer 更多

18、PageSliderIndicator【滑动页面指示器】

18.1、PageSliderIndicator 是什么?

简单:滑动页面指示器
官方:PageSliderIndicator,需配合PageSlider使用,指示在PageSlider中展示哪个界面。

18.2、简单使用

Harmony OS 组件篇_Harmony OS 常用组件_80

????这里是在之前的 PageSlider组件上新增代码进行实现,学习或源码可参考:
Harmony OS — PageSlider滑动页面

<PageSliderIndicator
    ohos:id="$+id:indicator"
    ohos:height="match_content"
    ohos:width="match_content"
    ohos:padding="8vp"
    ohos:layout_alignment="horizontal_center"
    ohos:top_margin="16vp"
    ohos:background_element="#55FFC0CB"/>
        PageSliderIndicator indicator = (PageSliderIndicator)findComponentById(ResourceTable.Id_indicator);
        ShapeElement normalElement = new ShapeElement();
        normalElement.setRgbColor(RgbColor.fromArgbInt(0xADD8E6));
        normalElement.setAlpha(168);
        normalElement.setShape(ShapeElement.OVAL);
        normalElement.setBounds(0, 0, 32, 32);
        ShapeElement selectedElement = new ShapeElement();
        selectedElement.setRgbColor(RgbColor.fromArgbInt(0x00BFFF));
        selectedElement.setAlpha(168);
        selectedElement.setShape(ShapeElement.OVAL);
        selectedElement.setBounds(0, 0, 48, 48);
        indicator.setItemElement(normalElement, selectedElement);
        indicator.setItemOffset(60);
        indicator.setPageSlider(pageSlider);

18.3、常用方法

(1)关联PageSlider

indicator.setPageSlider(pageSlider);

(2)响应页面更改事件

indicator.addOnSelectionChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int i, float v, int i1) {
            }
            @Override
            public void onPageSlideStateChanged(int i) {
            }
            @Override
            public void onPageChosen(int i) {
            }
 });

(3)设置所选指导航点的位置

indicator.setSelected(2);

此方法也会改变关联的PageSlider对象中的页面。

(4)自定义导航点的背景
除了上述使用Java创建背景外,也可以使用XML方式创建。

Harmony OS 组件篇_应用层开发_81

  • a.在graphic文件夹下创建selected_page_bg_element.xml。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="rectangle">
    <corners
        ohos:radius="16px"/>
    <bounds
        ohos:top="0"
        ohos:left="0"
        ohos:right="64px"
        ohos:bottom="32px"/>
    <solid
        ohos:color="#00BFFF"/>
</shape>
  • b.在graphic文件夹下创建unselected_page_bg_element.xml。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:ohos="http://schemas.huawei.com/res/ohos"
       ohos:shape="oval">
    <bounds
        ohos:top="0"
        ohos:left="0"
        ohos:right="32px"
        ohos:bottom="32px"/>
    <solid
        ohos:color="#ADD8E6"/>
</shape>
  • c.在Java代码中调用,设置导航点背景。
    ShapeElement normalElement = new ShapeElement(this, ResourceTable.Graphic_unselected_page_bg_element);
        ShapeElement selectedElement = new ShapeElement(this, ResourceTable.Graphic_selected_page_bg_element);
        indicator.setItemElement(normalElement, selectedElement);

(5)设置导航点之间的偏移量

indicator.setItemOffset(60);

18.4、更多

PageSliderIndicator 更多

喜欢记得点个赞哟,我是王睿,很高兴认识大家!