Android 自定义Toast、Dialog及Snackbar的使用技巧场景实例和小技巧

关于Toast、Dialog、Snackbar在日常开发中都是经常用到的控件,但在实际使用中,用哪个更好呢,或者假如系统的Dialog不能满足我们的业务要求了,是否可以做一些自定义呢,下面就总结复习下这方面的使用。

一、自定义Toast展示:


要点1:toast可以通过toast.setView()的方法,自定义其展示View。

要点2:SpannalbeStringBuilder可以对需要凸显的字体文本进行标注。

/**
     * 可以实现特殊字体标色,但是Toast中无法执行点击事件,也不建议执行该点击事件
     *
     * @param context
     * @param msg 整个文本
     * @param specialMsg 用颜色标注的文本
     * @param msgColor 整个文本的字体颜色
     * @param specialMsgColor 用颜色标注的文本的颜色
     */
    public static void ShowCustomToast(final Activity context, String msg, String specialMsg, int msgColor,
                                       final int specialMsgColor) {
        TextView textView = new TextView(context);
        textView.setTextColor(context.getResources().getColor(msgColor));
        textView.setBackgroundColor(context.getResources().getColor(R.color.gray_light));

        SpannableStringBuilder spannable = new SpannableStringBuilder(msg);

        Pattern pattern = Pattern.compile(specialMsg);
        Matcher matcher = pattern.matcher(msg);
        while (matcher.find()) {
            ClickableSpan what = new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    //该点击无效,同时toast用来展示和提示作用,不赞成使用toast做点击交互事件
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    //设置特殊显示文本的字体颜色
                    ds.setColor(context.getResources().getColor(specialMsgColor));
                    //设置是否有下划线
                    ds.setUnderlineText(false);
                }
            };

            spannable.setSpan(what, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            textView.setText(spannable);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        }

        Toast toast = new Toast(context);
        toast.setDuration(LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(textView);
        toast.show();
    }


使用示例:

ToastUtil.ShowCustomToast(getActivity(), "您已分享成功,记得到会员模块领取奖励噢", "会员", R.color.black, R.color.blue);

二、自定义Dialog:


要点1:区别于Toast,可以有点击事件

要点2:可以通过Handler.postDelayed方法随意设置Dialog的展示时间。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/root_layout"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_margin="20dp"
              android:background="@color/gray_light"
              android:gravity="center"
              android:orientation="vertical">

    <ImageView
        android:id="@+id/iv"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_gravity="center"
        android:padding="@dimen/margin_20dp"
        android:src="@drawable/animation"/>

    <LinearLayout
        android:id="@+id/ll_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="赞,成功分享给小伙伴"
            android:textColor="@color/black"/>

        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>


</LinearLayout>
package com.hongri.recyclerview.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.hongri.recyclerview.R;

/**
 * Created by zhongyao on 2018/2/28.
 * 自定义Dialog
 */

public class CustomDialog extends Dialog {
    private String msg = "已成功分享";
    private String msg2 = "搜索2018领取福利";
    private String msgAll = "已成功分享,快去领取福利吧";
    private String msgSpecial = "领取福利";

    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        setContentView(R.layout.layout_custom_toast_normal);

        initView2(context);
    }

    private void initView2(final Context context) {
        ImageView iv = (ImageView)findViewById(R.id.iv);
        TextView tv = (TextView)findViewById(R.id.tv);
        TextView tv2 = (TextView)findViewById(R.id.tv2);

        iv.setImageResource(R.drawable.toast_check_icon);
        tv2.setVisibility(View.GONE);

        SpannableStringBuilder spannable = new SpannableStringBuilder(msgAll);
        Pattern pattern = Pattern.compile(msgSpecial);
        Matcher matcher = pattern.matcher(msgAll);
        while (matcher.find()) {
            spannable.setSpan(new ClickableSpan() {
                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    ds.setColor(context.getResources().getColor(R.color.red));
                    ds.setUnderlineText(false);
                }

                @Override
                public void onClick(View widget) {
                    //可以定义点击事件(区别于自定义Toast)
                    ToastUtil.ShowBottomLong(context, msgSpecial);
                }
            }, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }

        tv.setText(spannable);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setHighlightColor(Color.TRANSPARENT); //设置点击后的颜色为透明
        setCancelable(true);
        setCanceledOnTouchOutside(true);
        getWindow().setGravity(Gravity.CENTER);
        getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
            1200);
    }

    
    /**
     * 可以控制Dialog的显示时间:
     * 效果上可以看做一个"自定义Toast",但是可以有点击事件
     * @param time 展示的时间
     */
    public void showView(int time) {
        this.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissView();
            }
        }, time);
    }
    public void dismissView() {
        this.dismiss();
    }
}


使用示例:

CustomDialog customDialog = new CustomDialog(getActivity(), R.style.AppTheme);
customDialog.showView(2000);

三、Snackbar使用:


Snackbar的使用需要在build.gradle的dependencies{ }中添加如下依赖:

compile 'com.android.support:design:25.4.0'

要点1:代码中view可以是改界面的任意View

要点2:在底部展示出来,并可以提供点击事件

public static void ShowSnackbar(final Context context, View view) {
        Snackbar.make(view, "分享成功", Snackbar.LENGTH_LONG).setAction("哈哈", new OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtil.ShowBottomShort(context, "点击事件");
            }
        }).show();
    }

使用示例:

SnackbarUtil.ShowSnackbar(getActivity(),root_layout);


发布了95 篇原创文章 · 获赞 195 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/u012440207/article/details/79416787