如果希望定制 Toast 的显示效果,比如字体大小,颜色,或者是显示一些图片。这时就需要用到自定义的 Toast 了。
在本示例中,我们将建立一个包含文字和图片的自定义Toast。
准备素材
在网上随便下载一张png图片,下载以后,将图片复制到 res 下的 drawable 目录中,比如文件名为: alert_256px.png, 拷贝完成以后,在 Android Studio 中看到的项目文件结构应该是这样:
1 2 3 4 5 6 7 8 9
| app + manifests + java + generatedJava + res + drawable alert_256px.png ic_launcher_background.xml ic_launcher_foreground.xml
|
构建显示内容
新建一个 layout 文件,用于描述 Toast 将要如何显示。 选择 app, 右键选择 New -> XML -> Layout XML File。
根据提示为文件命名并选择布局管理器。 示例中文件命名为: custom_toast.xml。
然后在 layout 中增加一个 ImageView 和一个 TextView, 在添加 ImageView 时,根据提示选择显示刚才拷贝的那个文件。对于 TextView, 也可以选择字体大小和颜色等。
最终的 custom_toast.xml文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/custom_toast_layout" android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView android:id="@+id/imageView" android:layout_width="196dp" android:layout_height="159dp" android:layout_marginStart="108dp" android:layout_marginLeft="108dp" android:layout_marginEnd="108dp" android:layout_marginRight="108dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:srcCompat="@drawable/alert_256px" />
<TextView android:id="@+id/toastTitle" android:layout_width="280dp" android:layout_height="58dp" android:layout_marginTop="8dp" android:text="Hello World" android:textSize="36sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.498" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintVertical_bias="0.046" /> </androidx.constraintlayout.widget.ConstraintLayout>
|
构造、显示自定义的Toast
编辑完 layout 文件以后,接下来就可以构造 Toast 类并显示了。代码如下:
1 2 3 4 5 6 7 8
| LayoutInflater li = getLayoutInflater(); View layout = li.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.custom_toast_layout));
Toast toast = new Toast(getApplicationContext()); toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setView(layout); toast.show();
|
在代码的前两行中,我们通过 LayoutInflater 类的 inflate 方法将一个 layout 文件转换为一个 View 类。然后再初始化一个 Toast 类,第7行时关键,我们将根据xml文件构造出来的View类,贴到Toast中,这样 toast 就显示了 layout 文件中描述的界面内容。