目录(两种使用方式):
官网链接: https://developer.android.google.cn/guide/topics/ui/notifiers/toasts
声明:以下代码完全是官网摘抄!
1.一句话简单使用:
Toast.makeText(this, "需要提示的字符串信息", Toast.短或长).show();
// 没什么好说的,前面的部分是实例化一个对象,最后调用对象的show()方法显示出来。
2.高级定制:xml静态+代码动态
0.熟悉一个方法,下面要用:定制位置:
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
//第一个位置参数:布局对齐方式(如上:上TOP左LEFT对齐)
//第二第三参数:添加坐标 x,y,让它更符合你的设定
1.xml:文件名——>layout/custom_toast.xml
必须为线性布局设置id,因为我们还要在代码中设定:
看到如下代码,你的头脑应该浮现一根水平线,线上先后排序一张图片和一个文本。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="#DAAA"
>
<ImageView android:src="@drawable/droid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF"
/>
</LinearLayout>
2.代码中设定:
java:
//获取当前环境下的LayoutInflater对象
LayoutInflater inflater = getLayoutInflater();
//使用上面获取到的对象的inflate方法获取View对象
View layout = inflater.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.custom_toast_container));
//使用View对象的方法获取子对象(TextView类型)
TextView text = (TextView) layout.findViewById(R.id.text);
//动态设置TextView的文本
text.setText("This is a custom toast");
Toast toast = new Toast(getApplicationContext());//其实就是this
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);//设置位置
toast.setDuration(Toast.LENGTH_LONG);//设置长短
toast.setView(layout);//关键:使用上面创建和配置的View对象
toast.show();//最终显示出来
kotlin:
val inflater = layoutInflater
val container: ViewGroup = findViewById(R.id.custom_toast_container)
val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
val text: TextView = layout.findViewById(R.id.text)
text.text = "This is a custom toast"
with (Toast(applicationContext)) {
setGravity(Gravity.CENTER_VERTICAL, 0, 0)
duration = Toast.LENGTH_LONG
view = layout
show()
}