自定义Toast、View

来源:互联网 发布:北京工业软件开发 编辑:程序博客网 时间:2024/06/06 00:05

Toast

一个toast可以看做是给用户的一个简单信息反馈,告诉人们目前对于程序的操作是怎样的。通常它显示在屏幕的中间偏下方,黑色且透明,默认持续时长2秒左右。下面贴出一张手机截图。
这里写图片描述

注意: 如果遇到打不开的链接,请检查是否可以科学上网。

1. 最基本的toast

这里写图片描述

  • 首先实例化一个 toast, 调用它的 makeTest() 方法填入相应的参数,且调用 show() 方法,此时 toast 将显示出来。下面给出 示例:
    注意:参数中的 context!一般 android 程序中很容易出现 context 泄露,这里为了避免程序中 context 内存泄露,使用的是 ApplicationContext,所以能用 ApplicationContext 的地方尽量使用ApplicationContext 。(具体怎样泄露的网上自己看看,一抓一大把),贴个链接–> context泄露
Context context = getApplicationContext();CharSequence text = "Hello toast!";int duration = Toast.LENGTH_SHORT;Toast toast = Toast.makeText(context, text, duration);toast.show();

2. 自定义位置的 toast

这里写图片描述

  /**     * 屏幕中间显示toast 无图片     */    public static void showCenterToast(Context context, String string) {        try {            if (context == null) return;            if (toast != null)                toast.cancel();            toast = Toast.makeText(context, string, Toast.LENGTH_SHORT);            toast.setGravity(Gravity.CENTER, 0, 0);            toast.show();        } catch (Exception e) {            e.printStackTrace();        }    }

2. 自定义 UI 的 toast

注:自定义 toast 背景、圆角、文字颜色、添加图片
这里写图片描述

/**     * 自定义 toast 背景、圆角、文字颜色、添加图片     *      * 如果图片需要适应不同的场景,可以单独提出来的     */   public static void showCustomToast(Context context, String string) {        try {            if (context == null) return;            if (toast != null) {                toast.cancel();            }            toast = new Toast(context);            toast.setDuration(Toast.LENGTH_SHORT);            TextView textView = new TextView(context);            ImageView imageView = new ImageView(context);            LinearLayout layout = new LinearLayout(context);            layout.setBackgroundResource(R.drawable.sha_bord_cir_gray);                             // 设置 toast 背景颜色            layout.setPadding(10,10,10,10);                                                         // 设置 toast 的 padding 大小            layout.setGravity(Gravity.CENTER);                                                      // 设置 toast 居中显示            imageView.setBackgroundResource(R.mipmap.ic_launcher);            textView.setTextColor(Color.RED);            textView.setText(string);            layout.addView(imageView);            layout.addView(textView);            toast.setView(layout);            toast.show();        } catch (Exception e) {            e.printStackTrace();        }    }

到这里 toast 的介绍就完毕了,如遇什么问题,可以发信息给我哦 q:1551121393。
**付出是种不易,心意到就行,觉得有帮助再打赏!
这里链接贴上–>下载**

这里写图片描述

付出是种不易,心意到就行,觉得有帮助再打赏!
这里写图片描述

1 1
原创粉丝点击