首先创建mytoast.xml
mytoast.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:orientation="vertical">
<Text
ohos:id="$+id:msg"
ohos:height="match_content"
ohos:width="match_content"
ohos:text_size="20fp"
ohos:text_color="#FFFFFF"
ohos:text_alignment="center"
ohos:background_element="#464343"
/>
</DirectionalLayout>
然后创建ToastUtils.java
package com.example.dialogapplication.MyToastUtils;
import com.example.dialogapplication.ResourceTable;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.Text;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
public class ToastUtils {
public static void showDialos(Context context,String str){
//1.把xml文件加载到内存当中
DirectionalLayout dl = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_mytoast, null, false);
//2.获取当前布局对象中文本组件
Text msg = (Text) dl.findComponentById(ResourceTable.Id_msg);
//3.把需要提示的信息设置到文本组件中
msg.setText(str);
//4.创建一个吐司对象
ToastDialog td = new ToastDialog(context);
//设置吐司的大小,默认是包裹内容,也可以手动再设置一遍
td.setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT,DirectionalLayout.LayoutConfig.MATCH_CONTENT);
//设置出现的时间
td.setDuration(2000);
//设置对齐方式
td.setAlignment(LayoutAlignment.BOTTOM);
//设置偏移
td.setOffset(0,200);
//xml布局交给吐司
td.setContentCustomComponent(dl);
//显示认吐司
td.show();
}
}
MainAbilitySlice.java代码:
package com.example.dialogapplication.slice;
import com.example.dialogapplication.MyToastUtils.ToastUtils;
import com.example.dialogapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.tubecore.AVTubeManager;
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
@Override
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//1.找到按钮
Button btn = (Button) findComponentById(ResourceTable.Id_btn);
//添加点击事件
btn.setClickedListener(this);
}
@Override
public void onActive() {
super.onActive();
}
@Override
public void onForeground(Intent intent) {
super.onForeground(intent);
}
@Override
public void onClick(Component component) {
ToastUtils.showDialos(this,"这是一个吐司弹框!");
}
}
最终效果: