【Android】---Toast Detailed Explanation

Toast will only pop up a piece of information to tell the user that something has happened, and it will automatically send a message after a period of time.
It will not block any operation of the user, and even the user can completely ignore the Toast
rendering:
insert image description here

1. Implementation code:

//第一个参数为当前的上下文环境。可用getApplicationContext()或者getContext()或this
//第二个参数为你要浮现的内容
//第三个参数设置浮现时间的长短,Toast.LENGTH_SHORT 和 Toast.LENGTH_LONG
//.show()是将Toast显示出来
Toast.makeText(context,"显示的文字",Toast.LENGTH_SHORT).show();

2. Modify the display position of Toast

Method 1: setGravity

Toast toast = Toast.makeText(context,"显示的文字",Toast.LENGTH_SHORT);
//三个参数分别表示(起点位置,水平向右位移,垂直向下位移)
toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM, 0, 10); //设置文本的位置,使文本显示靠下一些  

toast.show();

Method 2: setMargin

如果希望对显示位置进行较大幅度的调整,建议使用了setMargin方法
setMargin接受的参数分别是横向和纵向的百分比,这样在不同分辨率下的适应力更好。
此处是修改为在屏幕纵向正中间的上方显示
Toast toast = Toast.makeText(this, "Toast text with specific margin and position", Toast.LENGTH_SHORT);  
  toast.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.BOTTOM, 0, 0);  
  toast.setMargin(0f, 0.5f);  
  toast.show();  

3. Modify the appearance of Toast

1. Modify the background color of Toast

LinearLayout layout = (LinearLayout) toast.getView();
layout.setBackgroundColor(Color.parseColor("#F5F5F5"));  //设置toast的背景颜色

2. Modify the font of Toast

TextView v = (TextView) toast.getView().findViewById(android.R.id.message); //toast显示的文本内容
v.setTextColor(Color.RED);   //设置toast的字体颜色
v.setTextSize(20);           //设置toast的字体大小

Guess you like

Origin blog.csdn.net/weixin_45265547/article/details/125263373