?
3月26日追加:
完全自己实现Toast效果,信息由windowManager直接绘在屏幕上 用Handler延时取消
和系统Toast已经无任何关联了。。。。
注意 ?必须获得当前Activity的context对象 ? ApplicationContext/Service不可使用
appwidget中不可使用
?
package xxxxx;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
importxxxxxx;
/**
*
* @author DK App内所有Toast均使用本类管理 每个触发的Toast都会显示 *
* 不存在延迟Toast现象
*/
public class ToastUtil {
static TextView tv;
static WindowManager mWindowManager;
public static void showMessage(final Context act, final String msg) {
showMessage(act, msg, Toast.LENGTH_SHORT);
}
public static void showMessage(final Context act, final int msg) {
showMessage(act, act.getString(msg), Toast.LENGTH_SHORT);
}
public static void showMessage(Context context, String msg, int Length) {
mWindowManager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
if(tv==null)
{
tv = new TextView(context);
tv.setTextSize(24);
tv.setTextColor(0xff000000);
tv.setBackgroundResource(R.drawable.bg_appwidget_toast);
tv.setPadding(5, 5, 5, 5);
}
tv.setText(msg);
if (tv.getParent() == null) {
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.gravity = Gravity.BOTTOM;
params.alpha = 0.85f;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
params.format = PixelFormat.TRANSLUCENT;
params.verticalMargin=0.2f;
params.windowAnimations = 0;
mWindowManager.addView(tv, params);
handler.sendEmptyMessageDelayed(101, 2000);
} else {
handler.removeMessages(101);
handler.sendEmptyMessageDelayed(101, 2000);
}
}
static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (tv.getParent() != null)
mWindowManager.removeView(tv);
}
};
public static void cancelCurrentToast() {
if (tv != null && tv.getParent() != null) {
mWindowManager.removeView(tv);
}
}
}