最近想搞一个通知提示,但是由于使用场景限制,最后决定使用Toast来实现通知的提示。虽然Toast可以进行自定义,但是还是达不到自己想要的效果。最后翻来覆去终于找到了解决方法,特此献上!
源码:代码里有一块操作比较骚,通过反射的方式来获取到了Toast的WindowManager,思来想去,佩服了!
package xx.xx.xx;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
import com.starnet.stbsystemservice.R;
import java.lang.reflect.Field;
public class PushToast {
private final Context mContext;
private Toast mToast;
public PushToast(Context context) {
mContext = context;
}
public void createToast(String title, String content) {
if (mContext == null) {
return;
}
LayoutInflater inflater = LayoutInflater.from(mContext);
@SuppressLint("InflateParams") View view = inflater.inflate(R.layout.view_push_toast, null);
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
TextView tvContent = (TextView) view.findViewById(R.id.tv_content);
tvTitle.setText(title);
tvContent.setText(content);
mToast = new Toast(mContext);
mToast.setView(view);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.setGravity(Gravity.TOP, 0, 0);
initLayoutParams();
}
public void show(){
mToast.show();
}
private void initLayoutParams() {
try {
Object mTN;
mTN = getField(mToast, "mTN");
if (mTN != null) {
Object mParams = getField(mTN, "mParams");
if (mParams instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams;
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Object getField(Object object, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field field = object.getClass().getDeclaredField(fieldName);
if (field != null) {
field.setAccessible(true);
return field.get(object);
}
return null;
}
}
布局文件:
使用方法:
PushToast mToast = new PushToast(context);
mToast.createToast("通知: ","您的画质已经是最佳状态!");
mToast.show();
参考链接:
https://www.jb51.net/article/148988.htmhttps://www.jb51.net/article/148988.htm


![[安卓] 实现悬浮通知效果 [安卓] 实现悬浮通知效果](http://www.mshxw.com/aiimages/31/703962.png)
