自定义Toast

本文详细介绍了如何在Android中自定义Toast通知,包括创建自定义Toast所需的XML文件、设置属性以及实际应用的步骤。通过实例演示了如何在Activity中使用自定义Toast,并展示了最终的效果。

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

Toast通知十分方便,比起Dialog,不受Activity生命周期的影响(当Activity finish()之后,Toast依然可以存在)。

Android自带组件的风格都很挫,跟iOS没法比,直接拿来用的情况几乎没有,都需要自定义。包括这个Toast。

step1、自定义Toast要用的xml文件

step2、new Toast()

step3、设置新建的toast的属性,Toast已经有很多设置可以设置,十分方便。

xml文件:

<? xml version= "1.0" encoding= "utf-8" ?>
< LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"
    android:layout_width= "match_parent"
    android:layout_height= "match_parent"
    android:orientation= "vertical" >
   
    <LinearLayout
        android:layout_width= "450dp"
        android:layout_height= "50dp"
        android:background= "#000000"
        android:orientation= "vertical"
        >
        <TextView
            android:id= "@+id/my_txt"
            android:layout_gravity= "center"
            android:layout_width= "wrap_content"
            android:layout_height= "wrap_content"
            android:textSize= "30sp"
            android:text ="helloworld"
            android:textColor= "#ffffff"
            />
    </LinearLayout >
   
</ LinearLayout>

新建Toast,设置属性:

public class ShowUtils{
     
      public static Toast myToast;
      public static void ShowToast(Context context, String str, int duration){
            if( myToast == null){
                 myToast = new Toast(context);
           }
           View view = View. inflate(context, R.layout.toast_layout , null);
           TextView text = (TextView)view.findViewById(R.id.my_txt );
           text.setText(str);
            myToast.setDuration(duration);
            myToast.setGravity(Gravity. CENTER, 0, 10);
            myToast.setView(view);
            myToast.show();
     }
}

使用:
ShowUtils. ShowToast(MainActivity. this"helloworld" , 1000);

效果:


ctrlz presents! 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值