自定义Toast

来源:互联网 发布:淘宝直通车基础题答案 编辑:程序博客网 时间:2024/05/18 01:40
Toast是一种轻量级提示工具,而且提示并不会聚焦,所以并不会影响用户的操作,在Toast上一个层级的activity依旧会是Resume状态,并不会进入Pause。通常我们只是使用Toast的默认布局和纯文字显示,但是Toast是可以根据我们的需求进行功能自适应调整的。

1.默认Toast

//显示的上下文、内容、时间Toast toast=Toast.makeText(context,text,duration);//显示toast.show();

视图:
默认Toast
2.Toast位置可调整

//显示的上下文、内容、时间Toast toast=Toast.makeText(context,text,duration);//设置位置、x轴偏移量、y轴偏移量toast.setGravity(Gravity.TOP, int xOffset, int yOffset);//显示toast.show();

视图:
调整位置Toast
3.包含图片的Toast

//显示的上下文、内容、时间Toast toast=Toast.makeText(context,text,duration);//利用getView获得View对象,并强制转化为linearlayoutLinearLayout ll=(LinearLayout)toast.getView();//创建一个ImageView对象,并且设置图片ImageVIew iv=new ImageView(this);iv.setImageResource(R.mipmap.ic_launcher);//将image添加进toast的布局中ll.addView(iv);//显示toast.show();

视图:
含图片的Toast
4.自定义Toast
因为自定义Toast需要借助xml文件来布局我们的显示效果,所以该内容还会贴出xml布局文件
layout文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:orientation="vertical"              android:layout_width="match_parent"              android:layout_height="match_parent">    <ImageView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:src="@mipmap/ic_launcher"/>    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="这是自定义TOast"/></LinearLayout>

java源代码:

//创建一个Toast对象Toast toast=new Toast(this);返回一个填充了自定义布局的viewView view = LayoutInflater.from(this).inflate(R.layout.sublist,null);//将view添加到Toast中toast.setView(view);//显示Toasttoast.show();

视图:
自定义Toast

0 0
原创粉丝点击