public class MyToast{
long mDurationMillis;
private Context mContext;
Dialog builder;
Handler ha=new Handler();
View view;
public static MyToast makeText(Context context, String text, long duration) {
return new MyToast(context,text,duration);
}
public MyToast(Context context,String text,long duration) {
view = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT).getView();
if (view != null) {
TextView tv = (TextView) view.findViewById(android.R.id.message);
tv.setText(text);
}
setDuration(duration);
builder=new Dialog(context,R.style.Toast); //先得到构造器
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT );
builder.addContentView(view,params);
Window window = builder.getWindow();
// 可以在此设置显示动画
WindowManager.LayoutParams wl = window.getAttributes();
wl.y = ((Activity)context).getWindowManager().getDefaultDisplay().getHeight()/5;
// 以下这两句是为了保证按钮可以水平满屏
wl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
// 设置显示位置
builder.onWindowAttributesChanged(wl);
}
/**
* Set the location at which the notification should appear on the screen.
*
*/
public MyToast setDuration(long durationMillis) {
if (durationMillis < 0) {
mDurationMillis = 0;
}
if (durationMillis == Toast.LENGTH_SHORT) {
mDurationMillis = 2000;
} else if (durationMillis == Toast.LENGTH_LONG) {
mDurationMillis = 3500;
} else {
mDurationMillis = durationMillis;
}
return this;
}
public void show() {
builder.show();
ha.postDelayed(new Runnable() {
@Override
public void run() {
if(builder.isShowing()) {
try {
builder.cancel();
}catch (IllegalArgumentException e){
}
}
}
}, mDurationMillis);
}
public void setText(String text) {
TextView tv = (TextView) view.findViewById(android.R.id.message);
tv.setText(text);
}
}