自定义Toast
public static Toast TOAST;
public static void showToast(Context context, String string) {
if (context == null) {
return;
}
makeText(context, string + "", Toast.LENGTH_SHORT);
}
/**
* 显示提示信息,如果已经存在,把已经存在的关闭,重新打开一个
*
* @param context
* @param resid
* 文字信息资源id
* @param duration
* 显示时间
*/
public static void makeText(Context context, String resid, int duration) {
if (TOAST != null) {
TOAST.cancel();
TOAST = null;
}
context = context.getApplicationContext();
TOAST = new Toast(context);
TOAST.setDuration(duration);
addToastTextView(context, TOAST, resid);
TOAST.show();
}
public static void addToastTextView(Context context, Toast toast,
CharSequence msg) {
TextView view = new TextView(context);
view.setText(msg);
view.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
view.setTextColor(Color.WHITE);
view.setPadding(30, 30, 30, 30);
view.setBackgroundResource(R.drawable.shape_toast_bg);
toast.setView(view);
}
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<!-- 填充颜色 -->
<solid android:color="#90000000" />
<!-- <padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp" /> -->
<corners android:radius="4dp" />
</shape>
退出代码
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if ((System.currentTimeMillis() - mExitTime) > EXIT_TIME) {
Tools.showToast(mContext, "再按一次退出程序");
mExitTime = System.currentTimeMillis();
} else {
BaseApp.getInstance().killself();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
解决Toast不消失核心代码
private void cancelToast() {
if (Tools.TOAST != null) {
Tools.TOAST.show();
Tools.TOAST.cancel();
Tools.TOAST = null;
}
}
并没有卵用,activity onDestory方法没执行, 导致主界面异常退出,修改逻辑,杀死进程代码放在主界面的onDestory里 解决~
然而上面说的在onDestory里面,测试时,还是不能保证toast消失
以下代码,测试稳定................无副作用~
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
Tools.showToast(BaseApp.getAppContext(), "再按一次退出程序");
Looper.loop();
}
}.start();