Toast 自定义
.背景色 内边距 字体颜色和大小 显示位置
.不重复显示
.子线程中调用
package com.asen.jinan.widget;
import android.content.Context;
import android.graphics.Color;
import android.os.Looper;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;
import com.asen.jinan.R;
import com.asen.jinan.utlis.UnitUtil;
/**
* Created by yss on 2018/4/23.
* 自定义背景色 字体大小 颜色 内间距
* 同一内容的Toast不重复弹窗
*/
public class NoRepeatToast {
private static NoRepeatToast instance;
private NoRepeatToast() {
}
public static NoRepeatToast getInstance() {
if (instance == null) {
synchronized (NoRepeatToast.class) {
if (instance == null) {
instance = new NoRepeatToast();
}
}
}
return instance;
}
private Toast currentToast;
private String currentContent;
public void show(Context context, String content) {
if (TextUtils.isEmpty(content))
return;
if (currentToast != null) {
if (TextUtils.equals(content, currentContent)) {
currentToast.show();
return;
}
currentToast.cancel();
}
if (Looper.myLooper() != Looper.getMainLooper()) {
Looper.prepare();
currentToast = createCustomToast(context, content);
currentToast.show();
currentContent = content;
Looper.loop();
return;
}
currentToast = createCustomToast(context, content);
currentToast.show();
currentContent = content;
}
public void cancle() {
if (currentToast != null)
currentToast.cancel();
}
private Toast createCustomToast(Context context, String content) {
Toast customToast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
//view 可以通过 LayoutInflater.from(context).inflat(R.layout.yourview);
TextView view = new TextView(context);
view.setBackgroundResource(R.drawable.shape_toast_bg);
view.setText(content);
view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
float afterConvert = UnitUtil.getTypeVauleByUnit(context, TypedValue.COMPLEX_UNIT_DIP, 12);
int padding = new Float(afterConvert).intValue();
view.setPadding(padding, padding, padding, padding);
view.setTextColor(Color.WHITE);
customToast.setView(view);
customToast.setGravity(Gravity.BOTTOM, 0, 200);
return customToast;
}
}
view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
float afterConvert = UnitUtil.getTypeVauleByUnit(context, TypedValue.COMPLEX_UNIT_DIP, 12);
这里要做适配。字体大小sp和内间距dp
public class UnitUtil {
public static float getTypeVauleByUnit(Context mContext, int unit, int size) {
Resources res = mContext == null
? Resources.getSystem()
: mContext.getResources();
return TypedValue.applyDimension(unit, size, res.getDisplayMetrics());
}
}
