android定制化显示toast
16lz
2021-01-26
android开发者不可避免的会与toast打交道,这是一个全局提醒,只要用于消息的提示等等。但是不同的手机toast的展示形式可能会存在不一样,为此我们需要定制自己的Toast组件...(主要是通过加载自己的布局文件,定制化实现Toast对象)
(一)Toast的基础用法
Toast.makeText(context, "No network connection.", duration).show();
我们看一下makeText方法的实现:
/** * Make a standard toast that just contains a text view. * * @param context The context to use. Usually your {@link android.app.Application} * or {@link android.app.Activity} object. * @param text The text to show. Can be formatted text. * @param duration How long to display the message. Either {@link #LENGTH_SHORT} or * {@link #LENGTH_LONG} * */ public static Toast makeText(Context context, CharSequence text, @Duration int duration) { Toast result = new Toast(context); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null); TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message); tv.setText(text); result.mNextView = v; result.mDuration = duration; return result; }
主要是创建一个Toast对象,然后加载布局文件,设置显示msg的消息和时间长短。。。
其中Toast源码中定义了两个常量分别别是显示的时间长短:
/** * Show the view or text notification for a short period of time. This time * could be user-definable. This is the default. * @see #setDuration */ public static final int LENGTH_SHORT = 0; /** * Show the view or text notification for a long period of time. This time * could be user-definable. * @see #setDuration */ public static final int LENGTH_LONG = 1;
(二)自定义布局文件初始化Toast对象
// 创建 Toast 实例Toast toast = new Toast(getApplicationContext());// 创建自定义 viewView view = getLayoutInflater().inflate(R.layout.toast_view, null);// 设置自定义 viewtoast.setView(view);// 设置显示持续时间toast.setDuration(Toast.LENGTH_LONG);// 设置位置int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);// 显示 Toasttoast.show();
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/txtMessage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableStart="@drawable/ic_report_problem" android:drawablePadding="8dp" android:paddingTop="8dp" android:paddingBottom="8dp" android:paddingLeft="16dp" android:paddingRight="16dp" android:gravity="center" android:textColor="@android:color/white" android:textSize="16dp" android:text="No connection." android:background="@color/indigo"/>
更多相关文章
- Android(安卓)Studio轻松上手指南
- Android(安卓)的 Application 初始化
- Android设置AlertDialog点击按钮对话框不关闭
- 通过自定义View,创建一个圆形指示器
- view的几种布局方式及实践
- APP字体大小,不随系统的字体大小变化而变化的方法
- Fragment的API学习笔记
- Android中的内部类引起的内存泄露
- Android(安卓)ViewGroup.setDescendantFocusability函数