Toast的简化用法

1. 简介

刚开始用Toast的时候,经常记不住使用方法。当记得住使用方法的时候,有不喜欢其传统的啰嗦用法。所以,就根据周边看到的一些情况,梳理出本文的偷懒用法。


2. 方法一:静态方法,无须构造对象实例

代码如下:

package com.example.utils;

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

public class ToastUtils {

    public static void showShort(Context context, String msg) {
    	show(context, msg, Toast.LENGTH_SHORT);
    }
    
    public static void showLong(Context context, String msg) {
        show(context, msg, Toast.LENGTH_LONG);
    }
    
    private static void show(Context context, String msg, int duration) {
    	Toast.makeText(context, msg, duration).show();
    }
    
}

3. 方法二:需构造对象示例,但后续使用更加方便

package com.example.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.Toast;

@SuppressLint("ShowToast") 
public class ToastHelper {
	private Toast toast;
    
    public ToastHelper(Context context) {
        if (context == null) {
            throw new NullPointerException("Context can not be null!");
        }
        
        toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);
    }
    
    public void show(String msg) {
        toast.setText(msg);
        toast.show();
    }
    
    public void show(int resourceId) {
        toast.setText(resourceId);
        toast.show();
    }
}

4. 比较

第一种方法适用于调用不频繁的情况,但每次调用要传入Context等参数;第二种适合较大的类中调用,只需要在构造函数中创建一次ToastHelper实例,作为数据成员,后续直接调用show(),加上一个入参即可。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值