來一套不一樣的Toast--自定義Toast

Android默認ToastAndroid默認Toast只是一個簡單的黑框框欲芹,有時覺得太單調(diào)了枯冈,不如自己實現(xiàn)一套較精致华坦,不一樣的Toast撮躁。
先看下效果(動圖可能有點大):

前四個是不同類型的Toast,第五個是個loading框捺氢。它們兩者實現(xiàn)方式不同藻丢,分別進行講解

不一樣的Toast

Toast其實并不一定要是在底部彈出的黑色小框框,它也自定義不同的樣式

自定義顯示位置

toast的顯示位置可以通過 方法setGravity(int gravity, int xOffset, int yOffset)來設(shè)置摄乒,
參數(shù)1是位置有Gravity.BOTTOM悠反,Gravity.CENTER,Gravity.CENTER_HORIZONTAL等馍佑,參數(shù)2,3是相對于x軸斋否,y軸的偏移量,單位為pix挤茄,如果想設(shè)置為一定數(shù)量dp如叼,可以用以下方法將dp轉(zhuǎn)換為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來實現(xiàn)穷劈,應為它只能顯示1.5s或3s,那就用dialog來實現(xiàn)它踊沸,這里有一點要注意歇终,就是背景如何做到半透明,并且大小合適

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>

然后在創(chuàng)建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];
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谬返,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子日杈,更是在濱河造成了極大的恐慌遣铝,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件莉擒,死亡現(xiàn)場離奇詭異酿炸,居然都是意外死亡,警方通過查閱死者的電腦和手機涨冀,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門填硕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人蝇裤,你說我怎么就攤上這事廷支。” “怎么了栓辜?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵恋拍,是天一觀的道長。 經(jīng)常有香客問我藕甩,道長施敢,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任狭莱,我火速辦了婚禮僵娃,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘腋妙。我一直安慰自己默怨,他們只是感情好,可當我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布骤素。 她就那樣靜靜地躺著匙睹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪济竹。 梳的紋絲不亂的頭發(fā)上痕檬,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機與錄音送浊,去河邊找鬼梦谜。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的唁桩。 我是一名探鬼主播闭树,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼荒澡!你這毒婦竟也來了蔼啦?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤仰猖,失蹤者是張志新(化名)和其女友劉穎捏肢,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體饥侵,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡鸵赫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了躏升。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辩棒。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖膨疏,靈堂內(nèi)的尸體忽然破棺而出一睁,到底是詐尸還是另有隱情,我是刑警寧澤佃却,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布者吁,位于F島的核電站,受9級特大地震影響饲帅,放射性物質(zhì)發(fā)生泄漏复凳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一灶泵、第九天 我趴在偏房一處隱蔽的房頂上張望育八。 院中可真熱鬧,春花似錦赦邻、人聲如沸髓棋。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽按声。三九已至,卻和暖如春湃鹊,著一層夾襖步出監(jiān)牢的瞬間儒喊,已是汗流浹背镣奋。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工币呵, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓余赢,卻偏偏與公主長得像芯义,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子妻柒,可洞房花燭夜當晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,081評論 25 707
  • ¥開啟¥ 【iAPP實現(xiàn)進入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程扛拨,因...
    小菜c閱讀 6,402評論 0 17
  • 一、系統(tǒng)自帶Toast的源碼分析 1. Toast的調(diào)用顯示 學過Android的人都知道举塔,彈出一個系統(tǒng)API吐司...
    笑說余生閱讀 5,790評論 8 46
  • 玻璃的另一端 是他的靈魂 驚詫 怖怒 漂浮無依 想要吶喊 掙脫 殘破的軀干 它憤怒 瞧瞧啊 這哪里是我 它望向玻璃...
    三歲更程閱讀 153評論 2 1
  • 《初夏語絲》 春去無眠已覺曉绑警, 樓林何處聞啼鳥。 小城夜來風和雨央渣, 榴紅落英知多少计盒。 (丙申芒種前十日雨后偶成)
    細陽冰清閱讀 236評論 0 0