AlertDialog和Toast那点事

Dialog和Toast开发Android的程序员来说肯定是不陌生的,这个平时我们会经常用到的,经过我的研究发现了一点小的技巧,知道的朋友勿喷!

一、Dialog
     来说一下Dialog的基本用法,相信大家经常使用了:

AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(MainActivity.this);
mAlertDialog.setTitle("我的");
mAlertDialog.setMessage("你的");
mAlertDialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});
mAlertDialog.setNegativeButton("no", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {

    }
});
mAlertDialog.create().show();
代码很简单,但是如果我们用5.0以下的手机运行的时候会出现这种界面

这种可能是我们见得最多的一种风格了,但是我们用5.0以上的手机运行会出现不一样的风格,比如这个:


现在的这个Dialog是Material Design风格的,android会根据手机版本自动赋予不用的风格,但是我们就想在5.0一下的使用这种高大上的风格怎么办,Google也考虑到了这一点,如果你用的是studio开发的,你在new AlertDialog的时候你会发现他有两个包:


如果你想在5.0一下的版本使用Material Design风格,你就导入这个import android.support.v7.app.AlertDialog包,你在运行试试就知道了。

二、Toast

大家最常见的就是如果我连续点击5次按钮,他会按顺序不断地显示5次Toaskt,这体验非常不好:


如何才能优化一下体验呢,大家可以看一下这个方法:

<span style="font-size:14px;">/**
 * Created by Anonymous on 2016/7/29.
 */
public class ToastUtil {
    private static Toast mToast;

    public static void showToast(Context context, String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }
}</span>
我们再来运行一下:


这次的效果就不一样了,变得帅气一下了木有?

代码很简单,相信大家一看就会了,今天就先写到这里吧,欢迎大家评论指出问题!

猜你喜欢

转载自blog.csdn.net/u014752325/article/details/52065430