您的位置:首页 > 移动开发 > Android开发

自定义Toast,兼容那些安装时把通知关掉还问为啥不给提示的测试人员

2017-08-22 10:48 381 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android