來一套不一樣的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),應(yīng)為它只能顯示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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容