美文网首页
Harmony 鸿蒙 自定义Toast

Harmony 鸿蒙 自定义Toast

作者: _发强 | 来源:发表于2021-11-06 16:58 被阅读0次

直接上代码:

public class ToastUtil {

    public static void show(Context context, String message) {
        if (context == null) {
            return;
        }
        DirectionalLayout component = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_layout_toast, null, false);
        Text text = (Text) component.findComponentById(ResourceTable.Id_tvMessage);
        text.setText(message);
        new ToastDialog(context)
                .setContentCustomComponent(component)
                .setAlignment(LayoutAlignment.BOTTOM)
                .setTransparent(true)
                .show();
    }
}

这里我是用了 XML 写了一个布局,可以按需实现。
重要的一个属性

setTransparent(true) 

如果没有设置透明属性,最终的 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:background_element="$graphic:bg_toast"
    ohos:bottom_margin="80vp"
    ohos:orientation="vertical"
    >

    <Text
        ohos:id="$+id:tvMessage"
        ohos:height="match_content"
        ohos:width="match_content"
        ohos:left_margin="5vp"
        ohos:padding="10vp"
        ohos:right_margin="5vp"
        ohos:text="我是测试内容"
        ohos:text_alignment="center"
        ohos:text_color="$color:white_65"
        ohos:text_size="17fp"
        />

</DirectionalLayout>

相关文章

网友评论

      本文标题:Harmony 鸿蒙 自定义Toast

      本文链接:https://www.haomeiwen.com/subject/ptujzltx.html