//显示文本的Toast
public static void showTextToas(Context context, String message){
View toastview= LayoutInflater.from(context).inflate(R.layout.toast_text_layout,null);
TextView text = (TextView) toastview.findViewById(R.id.tv_message);
text.setText(message);
text.setPadding(30,15,30,15);
TextPaint textPaint = text.getPaint();
//获取TextView 显示的字符串宽度
float textPaintWidth = textPaint.measureText(message) + 60;
int width = MyUtils.getScreenWidth((Activity) context)-20;
//如果字符串宽度小于屏幕的宽度,toast就设置为字符串宽度
if(textPaintWidth < width){
width = (int)textPaintWidth;
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT);
text.setGravity(Gravity.CENTER);
text.setLayoutParams(params);
Toast toast = new Toast(context);
toast.setGravity(Gravity.CENTER,0,0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastview);
toast.show();
}
调整自定义toast的宽度根据字符串的宽度来自适应显示。
最新推荐文章于 2024-04-20 08:00:00 发布