Android自定义Toast的时长、位置、及显示的View

本文介绍如何在Android应用中自定义Toast的显示时长、位置及外观,包括使用自定义视图和设置精确的显示时间。

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

自定义时长

Android自带的两个时长
Toast.LENGTH_LONG 默认显示3.5秒
Toast.LENGTH_SHORT 默认显示2秒

如何让Toast在3.5秒内自定义显示长度:

public static void showShort(Context context, String msg, int duration) {
        final Toast toast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
        toast.show();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                toast.cancel();
            }
        }, duration);
    }

***注意duration为毫秒

自定义位置

关键代码

public void showToastTop(Context context, String msg) {
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.TOP, 0, 0);
        toast.show();
    }
    public void showToastCenter(Context context, String msg) {
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER|Gravity.RIGHT, 0, 0);
        toast.show();
    }
    public void showToastBottom(Context context, String msg) {
        Display display = getWindowManager().getDefaultDisplay();
        int height = display.getHeight();
        Toast toast = Toast.makeText(context,msg,Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, height / 6);
        toast.show();
    }

自定义View

添加一个自定义的布局toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/toast_shape"
    android:padding="10dp"
    android:minWidth="100dp">

    <TextView
        android:id="@+id/tv_toast"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="18dp"
        android:textColor="#FFFFFF"
        />
</LinearLayout>

其中toast_shape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="5dp"/>
    <solid android:color="#5c5c5c"/>
</shape>

关键代码

 public static void showToast(Context context, String msg) {
        Toast toast = new Toast(context);
        //设置Toast显示位置,居中,向 X、Y轴偏移量均为0
        toast.setGravity(Gravity.CENTER, 0, 0);
        //获取自定义视图
        View view = LayoutInflater.from(context).inflate(R.layout.toast, null);
        TextView tvMessage = (TextView) view.findViewById(R.id.tv_toast);
        //设置文本
        tvMessage.setText(msg);
        //设置视图
        toast.setView(view);
        //设置显示时长
        toast.setDuration(Toast.LENGTH_SHORT);
        //显示
        toast.show();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值