Harmony 鴻蒙 自定義Toast

直接上代碼:

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 寫了一個(gè)布局,可以按需實(shí)現(xiàn)。
重要的一個(gè)屬性

setTransparent(true) 

如果沒有設(shè)置透明屬性,最終的 Toast 會(huì)有一個(gè)系統(tǒng)的背景,達(dá)不到你自己想要的效果.

  • 貼上 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="我是測(cè)試內(nèi)容"
        ohos:text_alignment="center"
        ohos:text_color="$color:white_65"
        ohos:text_size="17fp"
        />

</DirectionalLayout>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容