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

发布于 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
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐