自学鸿蒙应用开发(5)- button组件

2020-12-31 15:01:34 浏览数 (1)

本文介绍在鸿蒙应用中button组件的基本用法。

增加按钮组件

如下代码中红色部分所示,在布局中增加button组件。

代码语言:javascript复制
<?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">
    <Component
        ohos:height="0vp"
        ohos:weight="3"
        ohos:width="match_parent"
        />
    <DirectionalLayout
        xmlns:ohos="http://schemas.huawei.com/res/ohos"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:layout_alignment="center"
        ohos:orientation="vertical">
        <Image
            ohos:id="$ id:image"
            ohos:width="match_content"
            ohos:height="match_content"
            ohos:layout_alignment="center"
            ohos:image_src="$media:DevEco"
            />
        <Button
            ohos:id="$ id:hello_button"
            ohos:width="match_content"
            ohos:height="match_content"
            ohos:text_size="27fp"
            ohos:text="Click me!"
            ohos:layout_alignment="center"
            ohos:background_element="$graphic:background_button"
            ohos:margin="15vp"
            ohos:right_padding="8vp"
            ohos:left_padding="8vp"
            />
    </DirectionalLayout>
    <Component
        ohos:height="0vp"
        ohos:weight="5"
        ohos:width="match_parent"
        />
</DirectionalLayout>

代码中按钮id被指定为hello_button,这个信息会在下面的响应代码中用到。

增加操作事件响应代码

如下面代码中红色部分所示,为button组件增加响应代码。

代码语言:javascript复制
    package com.example.helloharmony.slice;

import com.example.helloharmony.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;

public class ComponentAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_component);
        Button button = (Button) findComponentById(ResourceTable.Id_hello_button);
        // 为按钮设置点击事件回调
                button.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                new ToastDialog(getContext())
                        .setText("你好,鸿蒙!")
                        .show();
            }
        });
    }

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

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

代码中使用布局文件中指定的组件id选择【Cliek me!】按钮之后,为button组件增加了一段在画面底部显示“你好,鸿蒙!"信息的响应代码。需要注意的是id的格式:ResourceTable.Id_hello_button。

参考文档

https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ui-java-component-button-0000001051009585

0 人点赞