自定義Toast
public static Toast TOAST;
public static void showToast(Context context, String string) {
if (context == null) {
return;
}
makeText(context, string + "", Toast.LENGTH_SHORT);
}
/**
* 顯示提示信息檩赢,如果已經(jīng)存在吕嘀,把已經(jīng)存在的關(guān)閉,重新打開(kāi)一個(gè)
*
* @param context
* @param resid
* 文字信息資源id
* @param duration
* 顯示時(shí)間
*/
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;
}
}
并沒(méi)有卵用,activity onDestory方法沒(méi)執(zhí)行, 導(dǎo)致主界面異常退出,修改邏輯,殺死進(jìn)程代碼放在主界面的onDestory里 解決~
然而上面說(shuō)的在onDestory里面,測(cè)試時(shí),還是不能保證toast消失
以下代碼,測(cè)試穩(wěn)定................無(wú)副作用~
new Thread(){
@Override
public void run() {
super.run();
Looper.prepare();
Tools.showToast(BaseApp.getAppContext(), "再按一次退出程序");
Looper.loop();
}
}.start();