对于toast,很多人都是直接建一个工具类直接使用,当然大多数情况下这并没有错,然而这只是大部分情况,还有一小部分呢(没办法,坑爹的国产rom自定义修改的太厉害了),所以造成了魅族华为等一些机型上Toast并不会提示。解决办法:
1.在手机设置里面设置软件的通知栏打开(可能每个叫法不一样哈)
2.当然就是我们查看源码自己写一个了咯。
这里我已经写好了一个,用法如下:
1.在项目bulid.gradle中添加
allprojects {
repositories {
jcenter()
maven { url 'https://jitpack.io' }
}
2.在app的bulid.gradle中添加引用
compile 'com.github.lieweisi:MyToast:v0.1'
参考代码
MyToast.showLong(this,"哈罗!"); //使用方式与系统Toast相差不大,注意获取的Context是activity.this
这里将主要源码贴出:
package com.lieweisi.toastlib;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
public class ToastCustom {
private static final int MESSAGE_TIMEOUT = 2;
public static final int LONGTIME = 5;
private WindowManager wdm;
private double time;
private View mView;
private WindowManager.LayoutParams params;
private WorkerHandler mHandler;
private ToastCustom(Context context, String text, double time) {
wdm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
mHandler = new WorkerHandler();
Toast toast = new Toast(context);
LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflate.inflate(R.layout.toast, null);
TextView tv = (TextView) view.findViewById(R.id.toastText);
tv.setText(text);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(view);
mView = toast.getView();
setParams();
this.time = time;
}
public void setParams()
{
params = new WindowManager.LayoutParams();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.windowAnimations = R.style.anim_view;
params.type = WindowManager.LayoutParams.TYPE_TOAST;
params.setTitle("Toast");
params.gravity = Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM;
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
params.y=100;
}
public static ToastCustom makeText(Context context, String text, double time) {
ToastCustom toastCustom = new ToastCustom(context, text, time);
return toastCustom;
}
public void showSuccess() {
mView.setBackgroundResource(R.drawable.toast_bg);
wdm.addView(mView, params);
mHandler.sendEmptyMessageDelayed(MESSAGE_TIMEOUT, (long) (time * 1000));
}
public void showError() {
mView.setBackgroundResource(R.drawable.toast_bg);
wdm.addView(mView, params);
mHandler.sendEmptyMessageDelayed(MESSAGE_TIMEOUT, (long) (time * 1000));
}
public void cancel() {
wdm.removeView(mView);
}
private class WorkerHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_TIMEOUT:
cancel();
break;
}
}
}
}
相信看过源码的童鞋很快就会明白是怎么回事。当然这样也并不是所有的都能适配到,在7.0以上的一些手机上会存在权限获取不到情况,那就需要各位自行探讨了,好啦,今天就到这咯!