关于Toast的用法

来源:互联网 发布:免费域名注册永久 编辑:程序博客网 时间:2024/05/25 08:12
一:默认样式Toast.makeText(getApplicationContext(), "默认样式的Toast", Toast.LENGTH_SHORT).show();// 显示时间较短二:自定义吐司的位置
Toast toast = Toast.makeText(getApplicationContext(), "自定义位置 的Toast", Toast.LENGTH_LONG);//显示时间较长 toast.setGravity(Gravity.CENTER, 0, 0);// 居中显示 toast.show();

三:带图片的吐司
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();

四:完全自定义的吐司
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();

五:来自其他线程的吐司
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();
        }
    });
}
0 0
原创粉丝点击