自定义Toast及解决Toast的重复显示问题

我们时常会用到Toast,但是源生的Toast有时会满足不了我们的需求,这就需要我们自定义了。

首先,来一个Toast工具类:

public class MyToast {
    private Toast mToast;
    private TextView textView;
    public void showToast(Context context, String text){

        View toastView = LayoutInflater.from(context).inflate(R.layout.mytoast, null);

        if (mToast == null){
            mToast = new Toast(context);
            mToast.setView(toastView);
            textView = (TextView) toastView.findViewById(R.id.toastText);
            textView.setText(text);
        }else {
            textView.setText(text);
        }
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.show();
    }

    //取消Toast(用于退出当前界面的时候)
    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }
}
贴上xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <TextView
        android:alpha="0.9"
        android:id="@+id/toastText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/shapetoast"
        android:text="1245"
        android:gravity="center"
        android:textColor="#000"
        />

</LinearLayout>

然后就是MainActiviy:

public class MainActivity extends AppCompatActivity {

    private MyToast myToast;
    private Context context;

    //用来记录第几次点击,并且验证不会弹出多个Toast
    private int count = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        myToast = new MyToast();

        findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
                myToast.showToast(context, "第" + count + "次弹出自定的Toast");
            }
        });
    }

    //返回键退出
    @Override
    public void onBackPressed() {
        myToast.cancelToast();
        super.onBackPressed();
    }
}
Demo下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值