Toast用法

应用场景:弹出提示信息

主界面:

代码如下:

 @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);
    }

1.默认样式的Toast

代码如下:

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

2.自定义位置的Toast

代码如下:

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

3.带图片的Toast

代码如下:

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();

4.完全自定义的Toast

代码如下:

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();

5.来自其他线程的Toast

代码如下:

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

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

posted on 2012-09-24 09:45  Harvey Ren  阅读(15284)  评论(1编辑  收藏  举报

导航