弹窗系列:Toast类如何实现在任意Activity上显示提示?

  • 关于Toast源码中,如何一步一步实现显示提示, 这篇文章 Android Toast源码分析 写得很详细,可以参考。

  • 我们能不能根据Toast源码中的原理,自己实现一个简单的Toast提示了?当然可以。参考这篇文章:使用WindowManager自定义toast

  • 下面贴出,我改进后的代码:


public class Toast {
    public static final int LENGTH_SHORT = 0;
    public static final int LENGTH_LONG = 1;
    private static final int LONG_DELAY = 3500; 
    private static final int SHORT_DELAY = 2000; 
    private static Context context;
    private static WindowManager windowManager;

    public static Toast init(Context context) {
        Toast toast = new Toast();
        Toast.context = context.getApplicationContext();
        windowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        return toast;
    }

    public void show(String text) {
        show(text, LENGTH_SHORT);
    }

    public void show(final String text, int length) {
        final TextView textView = new TextView(context);
        textView.setBackgroundResource(android.R.drawable.toast_frame); //设置成官方原生的 Toast 背景
        textView.setText(text);

        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.type = WindowManager.LayoutParams.TYPE_TOAST;
        lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; //设置这个 window 不可点击,不会获取焦点,这样可以不干扰背后的 Activity 的交互。
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.format = PixelFormat.TRANSLUCENT; //这样可以保证 Window 的背景是透明的,不然背景可能是黑色或者白色。
        lp.windowAnimations = android.R.style.Animation_Toast; //使用官方原生的 Toast 动画效果

        windowManager.addView(textView, lp);
        textView.postDelayed(new Runnable() { // 指定时间后,取消 Toast 显示
            @Override
            public void run() {
                windowManager.removeView(textView);
            }
        }, length == LENGTH_SHORT ? SHORT_DELAY : LONG_DELAY);
    }

}

使用方法:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.init(MainActivity.this).show("hhh");
    }
}

猜你喜欢

转载自blog.csdn.net/zhangjin1120/article/details/113096693