因为产品需求,要紧挨着标题栏弹出一个吐司提示,所以重写了一个TopToast。
为了兼容android 7.0 以上的手机,需要获取到status_bar的高度,并在展示视图的时候计算这个高度。
public class MsgTopToast extends Toast {
private static MsgTopToast mMsgToast;
private final TextView mTvMsg;
private int mStatusBarHeight = 0;
public static void initToast(Context context) {
if (mMsgToast == null) {
mMsgToast = new MsgTopToast(context);
}
}
public static MsgTopToast geToast() {
return mMsgToast;
}
public MsgTopToast(Context context) {
super(context);
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.xw_layout_msg_top_toast, null);
mTvMsg = (TextView) view.findViewById(R.id.toast_tv_msg);
int statusBarHeight1 = -1;
//获取status_bar_height资源的ID
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
//根据资源ID获取响应的尺寸值
statusBarHeight1 = context.getResources().getDimensionPixelSize(resourceId);
}
mStatusBarHeight = statusBarHeight1;
setView(view);
}
public void setShortMsg(String msg) {
setDuration(Toast.LENGTH_SHORT);
mTvMsg.setText(msg);
show();
}
public void setShortMsg(int msg) {
setDuration(Toast.LENGTH_SHORT);
mTvMsg.setText(msg);
show();
}
public void setLongMsg(String msg) {
setDuration(Toast.LENGTH_LONG);
mTvMsg.setText(msg);
show();
}
public void setLongMsg(int msg) {
setDuration(Toast.LENGTH_LONG);
mTvMsg.setText(msg);
show();
}
@Override
public void show() {
int lastTitleBarHeightPx = TitleBarView.getLastMeasureHeightPx();
if (lastTitleBarHeightPx != 0) {
this.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, lastTitleBarHeightPx - 2);
}
super.show();
}
}