直接上代碼:
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>