-
關于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");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/252708.html
標籤:其他
