应用场景:弹出提示信息

主界面:

Toast用法-LMLPHP

代码如下:

Toast用法-LMLPHP
 @Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init()
{
defaultToastBtn = (Button) findViewById(R.id.defaultToastBtn);
customLocationBtn = (Button) findViewById(R.id.customLocationBtn);
imageToastBtn = (Button) findViewById(R.id.imageToastBtn);
customToastBtn = (Button) findViewById(R.id.customToastBtn);
otherThreadBtn = (Button) findViewById(R.id.otherThreadBtn); defaultToastBtn.setOnClickListener(this);// 设置监听
customLocationBtn.setOnClickListener(this);
imageToastBtn.setOnClickListener(this);
customToastBtn.setOnClickListener(this);
otherThreadBtn.setOnClickListener(this);
}
Toast用法-LMLPHP

1.默认样式的Toast

Toast用法-LMLPHP

代码如下:

Toast.makeText(getApplicationContext(), "默认样式的Toast", Toast.LENGTH_SHORT).show();// 显示时间较短

2.自定义位置的Toast

Toast用法-LMLPHP

代码如下:

Toast toast = Toast.makeText(getApplicationContext(), "自定义位置 的Toast", Toast.LENGTH_LONG);//显示时间较长 
toast.setGravity(Gravity.CENTER, 0, 0);// 居中显示
toast.show();

3.带图片的Toast

Toast用法-LMLPHP

代码如下:

Toast用法-LMLPHP
Toast toast = Toast.makeText(getApplicationContext(), "带图片的Toast", 3000);// 显示时间也可以是数字
toast.setGravity(Gravity.TOP, 0, 0);// 最上方显示
LinearLayout toastLayout = (LinearLayout) toast.getView();
ImageView imageView = new ImageView(getApplicationContext());
imageView.setImageResource(R.drawable.icon);
toastLayout.addView(imageView, 0);// 0 图片在文字的上方 , 1 图片在文字的下方
toast.show();
Toast用法-LMLPHP

4.完全自定义的Toast

Toast用法-LMLPHP

代码如下:

Toast用法-LMLPHP
LayoutInflater inflater = getLayoutInflater();// LayoutInflater对象
View layout = inflater.inflate(R.layout.custom_view, null);
ImageView imageView = (ImageView) layout.findViewById(R.id.imageView);
TextView text = (TextView) layout.findViewById(R.id.textView);
imageView.setImageResource(R.drawable.icon);
text.setText("完全自定义的Toast");
Toast toast = new Toast(getApplicationContext());
// 底部 、水平居中,X偏移50 Y偏移50
toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM, 50, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
Toast用法-LMLPHP

5.来自其他线程的Toast

Toast用法-LMLPHP

代码如下:

Toast用法-LMLPHP
handler = new Handler();
new Thread(new Runnable()
{
public void run()
{
show();
}
}).start();
Toast用法-LMLPHP
Toast用法-LMLPHP
private void show()
{
handler.post(new Runnable()
{
@Override
public void run()
{
Toast.makeText(getApplicationContext(), "Hello,I come from other thread!", 5000).show();
}
});
}
Toast用法-LMLPHP

注:getApplicationContext()  表示它的生命周期是整个应用,应用摧毁它才被摧毁。

05-11 19:57