本文例程下载:WillFlow_Toast、WillFlowMenu
一、什么是Toast?
Toast 也被叫做吐司,是 Android 系统提供的一种非常好的提醒方式,在程序中可以使用它将一些短小的信息通知给用户,它有如下两个特点:
- Toast 是没有焦点的
- Toast显示的时间有限过一定的时间就会自动消失
所以一般来讲Toast的使用并不会影响我们的正常操作,并且它通常不会占用太大的屏幕空间,有着良好的用户体验。
使用Toast的一般步骤:
1、调用Toast的构造器或者makeText()静态方法构造一个Toast对象。
2、调用Toast的方法来设置该消息的提醒方式、页边距等。
3、调用Toast的show()方法将它显示出来。
百闻不如一见:
我们现在就尝试一下如何在活动中使用 Toast。
二、Toast的四种使用方式
首先需要定义一个弹出 Toast 的触发点,那我们就在界面上定义几个按钮,当点击这个按钮的时候弹出对应的 Toast 。然后在 onCreate()方法中添加代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mButton1 = (Button) findViewById(R.id.button1);
mButton2 = (Button) findViewById(R.id.button2);
mButton3 = (Button) findViewById(R.id.button3);
mButton4 = (Button) findViewById(R.id.button4);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
}
其布局文件activity_main.xml为:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.wgh.willflow_toast.MainActivity">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="25dp"
android:text="默认Toast样式" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="25dp"
android:text="自定义显示位置效果" />
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="25dp"
android:text="带图片效果" />
<Button
android:id="@+id/button4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="25dp"
android:text="完全自定义效果" /><