记录一下自定义toast的宽度改变问题。
项目中没有完全修改Toast布局,只是在系统布局上添加了新的背景,修改了字号等小修改,但是出现了文字超过一定宽度之后,会换行显示。不太美观,测试的小姐姐让修改一下。一开始的解决方案是将字号变小,基本看不出差别。
之后研究跑马灯问题,想到了通过计算显示文本的宽度来设置Toast宽度。
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ToastUtil {
public TextView toastTextView = null;
public Toast toastView;
private boolean isShowToast = false;
private static ToastUtil toastUtil;
private ToastUtil() {
}
public static ToastUtil getInstance() {
if (toastUtil == null) {
toastUtil = new ToastUtil();
}
return toastUtil;
}
public Handler baseHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0: // 关闭 Toast
if (toastView != null && isShowToast) {
toastView.cancel();
isShowToast = false;
}
}
}
};
public void showWrapContentToast(Context conext, String str) {
if (toastView == null || toastTextView == null) {
toastView = Toast.makeText(conext, null, Toast.LENGTH_SHORT);
toastView.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastLayout = (LinearLayout) toastView.getView();
WindowManager wm = (WindowManager) conext.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(new DisplayMetrics());
toastTextView = new TextView(conext);
toastLayout.setBackgroundResource(R.drawable.popup_menu_bg);
toastTextView.setTextSize(40.0f);
toastLayout.setGravity(Gravity.CENTER);
Paint paint = new Paint();
Typeface typeface = Typeface.createFromAsset(conext.getAssets(), "fonts/Eurostile LT Medium.ttf");
paint.setTypeface(typeface);
paint.setTextSize(40);
int textValueWidth = getStringWidth(str, paint);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((textValueWidth + 40), LinearLayout.LayoutParams.WRAP_CONTENT);
// 这部分原来是下面这样,但是会出现显示不下换行的问题。
// LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, -51, 0, 0);
params.gravity = Gravity.CENTER;
toastTextView.setGravity(Gravity.CENTER);
toastTextView.setLayoutParams(params);
toastTextView.setTextColor(Color.parseColor("#bebebe"));
toastView.setView(toastLayout);
toastLayout.addView(toastTextView);
}
toastTextView.setText(str);
toastView.show();
isShowToast = true;
baseHandler.sendEmptyMessageDelayed(0, 2100); // 避免Toast不消失
}
/**
* 获取字符串显示所占宽度
* @param string 要显示的字符串
* @param paint 画笔
* @return 宽度
*/
private int getStringWidth(String string, Paint paint) {
Rect rect = new Rect();
paint.getTextBounds(string, 0, string.length(), rect);
return rect.width();
}
}