Android自定义Toast的时长、位置、及显示的View
16lz
2021-12-25
###Android自定义Toast
首先是自定义时长:
说是这么说,但是android自带的两个时长 LENGTH_SHORT (2秒) 和LENGTH_LONG (3.5秒)基本已经够用了,一般也没有特地去设置几十秒的Toast吧,这样的话,还不如直接弄一个Dialog来的直接。
我们先看看如何让Toast在3.5秒内自定义显示长度:
public static void showShort(Context context, String msg, int duration) { final Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG); toast.show(); new Handler().postDelayed(new Runnable() { public void run() { toast.cancel(); } }, duration); }
至于3.5秒之上的自定义时长,那么就可以通过休眠线程来实现
/** * @param context 传递的上下文 * @param msg 要显示的文本信息 * @param duration 自定义时长 */ public static void show(Context context, String msg, final int duration) { final Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG); final long startTime = System.currentTimeMillis(); toast.show(); new Handler().postDelayed(new Runnable() { public void run() { try { //线程开始休眠 Thread.sleep((long) (duration)); } catch (InterruptedException e) { e.printStackTrace(); } long entTime = System.currentTimeMillis(); Log.i("ToastUtil", "------>>>显示的时间为:" + (entTime - startTime)); } //这100毫秒只是用来让toast从隐藏到显示所给的时间,不然直接休眠线程的话,toast是无法显示出来的 }, 100); }
显示的时间长度如下图:10.191秒
这种方式基本别用,这可是直接让UI线程进行休眠啊,除非作用一些特殊场所,不然还是别用;如果实在还是要用,建议还是弄个Dialog自定义View去仿制一个Toast,这样自己想显示多长时间就显示多长时间。
接下来 自定义View 和 自定义位置就一起说了
首先是布局文件 R.layout.toast_view:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:background="@null" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:id="@+id/tv_message_toast" android:textColor="#fff" android:maxWidth="200dp" android:padding="15dp" android:textSize="18sp" android:gravity="center" android:drawableLeft="@drawable/btn_delete_red_circle" android:background="@drawable/shape_toast_bg" android:layout_height="wrap_content" />LinearLayout>
接着是Toast的方法
public static void show(Context context, String msg) { Toast toast = new Toast(context); //设置Toast显示位置,居中,向 X、Y轴偏移量均为0 toast.setGravity(Gravity.CENTER, 0, 0); //获取自定义视图 View view = LayoutInflater.from(context).inflate(R.layout.toast_view, null); TextView tvMessage = (TextView) view.findViewById(R.id.tv_message_toast); //设置文本 tvMessage.setText(msg); //设置视图 toast.setView(view); //设置显示时长 toast.setDuration(Toast.LENGTH_LONG); //显示 toast.show(); }
在Activity调用一下ToastUtil.show(this, "这是一个自定义视图和位置的Toast");
之后,显示的效果图如下:
布局可以自定义,虽然这个Toast有点丑,但是让大家知道怎么弄一个自定义Toast了。
更多相关文章
- Android(安卓)学习 笔记_01
- android TextView属性的详细介绍 分享
- 使用shape来定义控件的一些显示属性
- Android_TextView属性XML详解
- 如何在Android中用好多线程
- Android(安卓)-- Looper.prepare()和Looper.loop() —深入版
- Android之UI学习篇八:使用GridView实现九宫格的菜单
- Android(安卓)实用工具Hierarchy Viewer实战
- Android:TextView属性大全