鸿蒙自定义最简单ToastDialog 类;(可直接用) 原创

陈浩南xxx
发布于 2021-5-13 15:43
浏览
1收藏

一:效果图

鸿蒙自定义最简单ToastDialog 类;(可直接用)-鸿蒙开发者社区

二:调用demo

  private void show(String message) {
        MyToastDialog toastDialog = (MyToastDialog) new MyToastDialog(getContext())
            .setDuration(500)
            .setAlignment(LayoutAlignment.BOTTOM)
            .setOffset(0, 100);
        toastDialog.setText(message);
        toastDialog.show();
    }

三:代码

import ohos.agp.components.AttrHelper;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

/**
 * @since 2021-05-13
 */
public class MyToastDialog extends ToastDialog {

    public MyToastDialog(Context context) {
        super(context);
        init(context);
    }

    Text textComponent ;
    private void init(Context context){
        textComponent = new Text(context);

        int padding = 40;
        //设置间距为10vp
        textComponent.setPadding(padding, padding, padding, padding);
        textComponent.setTextColor(Color.BLACK);
        textComponent.setTextAlignment(TextAlignment.CENTER);
        textComponent.setTextSize(40);
        ShapeElement shapeElement = new ShapeElement(context, ResourceTable.Graphic_xtoast_frame);
        textComponent.setBackground(shapeElement);
        //设置文字允许多行
        textComponent.setMultipleLine(true);

        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig();
        layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_CONTENT;
        layoutConfig.height = ComponentContainer.LayoutConfig.MATCH_CONTENT;


        layoutConfig.alignment = LayoutAlignment.CENTER;
        textComponent.setLayoutConfig(layoutConfig);
        setTransparent(true);
        setComponent(textComponent);
       // setOffset(0, 100);

        setCornerRadius(AttrHelper.vp2px(ResourceTable.Float_xui_toast_radius, context));
    }

    @Override
    public MyToastDialog setText(String text) {
        textComponent.setText(text);
        return this;
    }
}

 

附 其他文件

xtoast_frame.xml

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

 

{
  "float": [
    {
      "name": "xui_toast_radius",
      "value": "30vp"
    }
  ]
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
已于2021-5-13 15:46:07修改
3
收藏 1
回复
举报
2条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

为楼主点赞

回复
2021-5-13 17:51:59
Whyalone
Whyalone

深得“Talk is Cheap,Show Me The Code”的精髓

回复
2021-5-15 00:11:22
回复
    相关推荐