android系列:Toast用法

本文详细介绍了 Android 中 Toast 的五种使用场景,包括默认样式、自定义位置、带图片、完全自定义以及来自其他线程的 Toast 实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用场景:弹出提示信息

主界面:

代码如下:

复制代码
 @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();
        }
    });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值