Android 自定义Toast

作者: CoderMiner | 来源:发表于2016-10-29 16:07 被阅读1312次

Android自定义Toast

题图 www.gratisography.com
  • Toast的基础用法
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT).show();
  • Toast显示的位置
    通常情况下Toast显示在整个界面的底部水平中间的位置,但是Toast现实的位置也是可以调整的,通过setGravity(int, int, int)
    方法来调整其位置
Toast toast = Toast.makeText(getApplicationContext(), "Normarl toast", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.RIGHT, 0, 0);
toast.show();
top_right.png
  • 自定义Toast
    创建自定义的layout文件,使用LayoutInflater渲染布局文件,最后使用ToastsetView(View)方法来实现

如果不是自定义Toast,请使用makeText(Context, int, int)方法来创建Toast,不要使用Toast的构造方法

自定义布局文件res/layout/custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>
<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/ic_action_discover"
               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"
              android:text="This is a custom toast"/>
</LinearLayout>

Java 代码逻辑

LayoutInflater inflater = getLayoutInflater();
              View view = inflater.inflate(R.layout.custom_toast, null);
              Toast toast = new Toast(getApplicationContext());
              toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
              toast.setDuration(Toast.LENGTH_SHORT);
              toast.setView(view);
              toast.show();
center.png
  • 点击一次显示一次Toast
    有时候连续点击会出现很多的Toast的提示,如果用户无操作,会导致toast提示一直存在,需要等很长时间
    才会消失,想要的效果是点击一次显示一次,
private Toast mToast;
private void showToast(String msg){
  if(mToast != null)
      mToast.cancel();
  mToast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
  mToast.show();
}

根据自己的需求开发不同类型的Toast

相关文章

网友评论

本文标题:Android 自定义Toast

本文链接:https://www.haomeiwen.com/subject/addyuttx.html