自定义Toast样式实践

5,311 阅读1分钟

需求是一个并不复杂的Toast,带一个图标,和有部分强调色的文字。

Toast示意

大概步骤如下:

  1. new 一个空的Toast
  2. 自定义自己的Toast布局并inflate成view
  3. 通过Toast.setView()设置自己的布局
  4. Toast.show()

自定义布局

使用LinearLayout,文字则使用使用html标签定义在string资源中。

Toast文字@string/text_diary_toast

<string name="text_diary_toast">
        保存成功!可在最新版app\n<font color="#28bea0">我的-创作和发言</font> 中查看
</string>

当然也可以使用SpannableString,更加灵活,这里就不展开了,有兴趣的同学自行搜索。

使用自定义shape_diary_toast资源为toast设置圆角背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <!-- 圆角设置 -->
    <corners android:radius="4dp" />

    <!-- 填充的颜色 -->
    <solid android:color="#cc333333" />
</shape>

最终布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_diary_toast"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="32dp"
        android:layout_height="32dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="18dp"
        android:src="@drawable/diary_toast_ic"
        android:layout_marginLeft="16dp" />

    <TextView
        android:id="@+id/diary_toast_tv"
        android:textColor="#ffffff"
        android:textSize="16sp"
        android:text="@string/text_diary_toast"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="20dp" />
</LinearLayout>

代码展示

private void showTipToast() {
    Toast toast = new Toast(this);
    LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View v = layoutInflater.inflate(R.layout.diary_toast, null);
    toast.setView(v);
    toast.show();
}

实机演示

实机展示

源码地址

in GitHub