記錄一下自定義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();
}
}