android高版本Toast问题

以前使用单例toast来保证连续点击不会一直弹toast,代码如下import android.content.Context;import android.os.Build;import android.widget.Toast;public class ToastUtil { private static Toast toast; public static vo...
摘要由CSDN通过智能技术生成

以前使用单例toast来保证连续点击不会一直弹toast,代码如下

import android.content.Context;
import android.os.Build;
import android.widget.Toast;

public class ToastUtil {
   

    private static Toast toast;

    public static void showToast(Context context, String content, int Duration) {
   
        if (toast == null) {
   
            toast = Toast.makeText(context, content, Duration);
        }
        else {
   
            toast.setText(content);
        }
        toast.show();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android Toast 默认的度是固定的,无法自适应内容的度。但是,你可以通过自定义布局文件来实现自适应度的 Toast。 首先,你需要创建一个自定义的 Toast 布局文件,例如命名为 custom_toast.xml: ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toast_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="16dp" android:background="@drawable/toast_background"> <TextView android:id="@+id/toast_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="@android:color/white" android:textSize="16sp"/> </LinearLayout> ``` 接下来,在你的代码中,你需要使用 LayoutInflater 加载该布局文件,并将其设置到 Toast 的 View 中。在设置 View 的同时,你还需要设置 Toast 的时长和位置: ``` // 加载自定义布局文件 View toastView = LayoutInflater.from(context).inflate(R.layout.custom_toast, null); // 设置Toast的文本内容 TextView toastText = (TextView) toastView.findViewById(R.id.toast_text); toastText.setText("Toast的文本内容"); // 创建Toast对象 Toast toast = new Toast(context); // 设置Toast的View toast.setView(toastView); // 设置Toast的时长和位置 toast.setDuration(Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); // 显示Toast toast.show(); ``` 最后,你需要注意的是,由于自定义的 Toast 布局文件中的度是 wrap_content,因此当文本内容过多时,Toast度可能会变得很大,这可能会影响用户体验。因此,你可以考虑在布局文件中添加一些限制条件,例如最大度或最大行数,以便在保证自适应度的同时,还能保持 Toast 的合理大小。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值