Android 自定义Toast

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容