来一套不一样的Toast--自定义Toast

Android默认ToastAndroid默认Toast只是一个简单的黑框框,有时觉得太单调了,不如自己实现一套较精致,不一样的Toast。
先看下效果(动图可能有点大):

前四个是不同类型的Toast,第五个是个loading框。它们两者实现方式不同,分别进行讲解

不一样的Toast

Toast其实并不一定要是在底部弹出的黑色小框框,它也自定义不同的样式

自定义显示位置

toast的显示位置可以通过 方法setGravity(int gravity, int xOffset, int yOffset)来设置,
参数1是位置有Gravity.BOTTOM,Gravity.CENTER,Gravity.CENTER_HORIZONTAL等,参数2,3是相对于x轴,y轴的偏移量,单位为pix,如果想设置为一定数量dp,可以用以下方法将dp转换为pix

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

或者

TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());

比如来显示一个相对于屏幕中心x偏上100pix的toast

Toast toast=Toast.makeText(this, "啦啦啦~",Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0,-100);
toast.show();

加个图标

Toast toast = Toast.makeText(getApplicationContext(),
                        "带图片的Toast", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout llToast = (LinearLayout) toast.getView();
ImageView ivIcon = new ImageView(getApplicationContext());
ivIcon.setImageResource(R.drawable.ic_info);
llToast.addView(ivIcon, 0);
toast.show();

完全自定义

Toast toast=Toast.makeText(this, "完全不一样", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);

View v= getLayoutInflater().inflate(R.layout.toast,null);
toast.setView(v);
toast.show();

toast.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:gravity="center"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
    android:background="@drawable/bg_toast">
    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="@dimen/toast_icon_size"
        android:layout_height="@dimen/toast_icon_size"
        android:src="@drawable/ic_info"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/toast_text"
        android:maxEms="12"
        android:layout_marginTop="@dimen/s_small_spacing"
        android:textSize="@dimen/sub_medium_text"/>
</LinearLayout>

效果就是开头动图里面前四种

同样式的loading

loading框的话显示时间不固定,不能用toast来实现,应为它只能显示1.5s或3s,那就用dialog来实现它,这里有一点要注意,就是背景如何做到半透明,并且大小合适

View view=LayoutInflater.from(context).inflate
                (R.layout.toast_loading,null);
TextView tv=view.findViewById(R.id.tv);
tv.setText(text);
AVLoadingIndicatorView avl=view.findViewById(R.id.avl);
avl.setIndicator(getIndicator(context));
avl.show();

dialog=new AlertDialog.Builder(context)
            .setView(view)
            .setCancelable(false)
            .create();
dialog.show();

AVLoadingIndicatorView 是一个loadingView的开源库,有多种样式,这里随机获取一种https://github.com/81813780/AVLoadingIndicatorView

toast_loading.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:orientation="vertical"
              android:gravity="center"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@drawable/bg_toast_loading">
    <com.wang.avi.AVLoadingIndicatorView
        android:id="@+id/avl"
        app:indicatorColor="@color/toast_text"
        app:indicatorName="LineScaleIndicator"
        android:layout_width="@dimen/toast_icon_size"
        android:layout_height="@dimen/toast_icon_size"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/toast_text"
        android:maxEms="12"
        android:layout_marginTop="@dimen/s_small_spacing"
        android:textSize="@dimen/sub_medium_text"/>
</LinearLayout>

然而出来的效果

这这效果。。。背景还是纯白,宽度不是wrap_content。这里需要自己写个dialog的theme,如下

<style name="CustomDialog" parent="android:Theme.Dialog">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
    </style>

然后在创建AlertDialog.Builder时传进去

dialog=new AlertDialog.Builder(context,R.style.CustomDialog)
                .setView(view)
...

再看效果

封装类

import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myframe.R;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.Random;

/**
 * Author:LvQingYang
 * Date:2017/8/18
 * Email:biloba12345@gamil.com
 * Github:https://github.com/biloba123
 *Blog:https://biloba123.github.io/
 * Info:
 */
public class MyToast {
    private static Toast toast;
    private static AlertDialog dialog;
    //info toast
    public static void info(Context context ,String text, int duration){
        showToast(context, R.drawable.ic_info, text, duration);
    }

    public static void info(Context context ,int textId, int duration){
        showToast(context, R.drawable.ic_info,context.getString(textId),duration);
    }

    public static void info(Context context ,String text){
        showToast(context, R.drawable.ic_info, text, Toast.LENGTH_SHORT);
    }

    public static void info(Context context ,int textId){
        showToast(context, R.drawable.ic_info,context.getString(textId),Toast.LENGTH_SHORT);
    }

    //success
    public static void success(Context context ,String text, int duration){
        showToast(context, R.drawable.ic_success, text, duration);
    }

    public static void success(Context context ,int textId, int duration){
        showToast(context, R.drawable.ic_success, context.getString(textId),duration);
    }

    public static void success(Context context ,String text){
        showToast(context, R.drawable.ic_success, text, Toast.LENGTH_SHORT);
    }

    public static void success(Context context ,int textId){
        showToast(context, R.drawable.ic_success, context.getString(textId),Toast.LENGTH_SHORT);
    }

    //error
    public static void error(Context context ,String text, int duration){
        showToast(context, R.drawable.ic_error, text, duration);
    }

    public static void error(Context context ,int textId, int duration){
        showToast(context, R.drawable.ic_error, context.getString(textId),duration);
    }

    public static void error(Context context ,String text){
        showToast(context, R.drawable.ic_error, text, Toast.LENGTH_SHORT);
    }

    public static void error(Context context ,int textId){
        showToast(context, R.drawable.ic_error, context.getString(textId),Toast.LENGTH_SHORT);
    }

    //loading
    public static void loading(Context context ,String text){
        View view=LayoutInflater.from(context).inflate
                (R.layout.toast_loading,null);
        TextView tv=view.findViewById(R.id.tv);
        tv.setText(text);
        AVLoadingIndicatorView avl=view.findViewById(R.id.avl);
        avl.setIndicator(getIndicator(context));
        avl.show();

        dialog=new AlertDialog.Builder(context,R.style.CustomDialog)
                .setView(view)
                .setCancelable(false)
                .create();
        dialog.show();
    }


    public static void loading(Context context ,int textId){
        loading(context, context.getString(textId));
    }

    //warning
    public static void warning(Context context ,String text, int duration){
        showToast(context, R.drawable.ic_warning, text, duration);
    }

    public static void warning(Context context ,int textId, int duration){
        showToast(context, R.drawable.ic_warning, context.getString(textId),duration);
    }

    public static void warning(Context context ,String text){
        showToast(context, R.drawable.ic_warning, text, Toast.LENGTH_SHORT);
    }

    public static void warning(Context context ,int textId){
        showToast(context, R.drawable.ic_warning, context.getString(textId),Toast.LENGTH_SHORT);
    }

    public static void cancel(){
        if (toast != null) {
            toast.cancel();
        }
        if (dialog != null) {
            dialog.cancel();
        }
    }

    static void showToast(Context context, int iconId, String text, int duration){
        if (toast != null) {
            toast.cancel();
        }
        toast=Toast.makeText(context, text, duration);
        toast.setGravity(Gravity.CENTER,0,0);

        View v= LayoutInflater.from(context).inflate
                (R.layout.toast,null);
        ImageView ivIcon=v.findViewById(R.id.iv_icon);
        ivIcon.setImageResource(iconId);
        TextView tv=v.findViewById(R.id.tv);
        tv.setText(text);

        toast.setView(v);
        toast.show();
    }

    private static String getIndicator(Context context)
    {
        String[] arrayOfString = context.getResources().getStringArray(R.array.arr_indicator);
        int i = new Random().nextInt(arrayOfString.length);
        return arrayOfString[i];
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,327评论 0 17
  • 一、系统自带Toast的源码分析 1. Toast的调用显示 学过Android的人都知道,弹出一个系统API吐司...
    笑说余生阅读 5,768评论 8 46
  • 玻璃的另一端 是他的灵魂 惊诧 怖怒 漂浮无依 想要呐喊 挣脱 残破的躯干 它愤怒 瞧瞧啊 这哪里是我 它望向玻璃...
    三岁更程阅读 149评论 2 1
  • 《初夏语丝》 春去无眠已觉晓, 楼林何处闻啼鸟。 小城夜来风和雨, 榴红落英知多少。 (丙申芒种前十日雨后偶成)
    细阳冰清阅读 231评论 0 0