Android自定义Toast样式和时间
说明:
Toast的样式自定义、显示时间自定义、消失时间自定义
代码:
1、效果图
2、调用代码:
new CustomToastSucc(FunctionListActivity.this).show("我是谁", 3000);
3000是显示3s
3、CustomToastSucc.java代码
package com.gxjl.pe.gxjlpesdk.util;
import android.content.Context;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.gxjl.pe.gxjlpesdk.R;
/**
* 自定义Toast - 正确提示
* Created by xiaoshuai on 2018/10/10.
*/
public class CustomToastSucc {
private boolean canceled = true;
private Handler handler;
private Toast toast;
private TimeCount time;
private TextView toast_content;
public CustomToastSucc(Context context) {
this(context, new Handler());
}
public CustomToastSucc(Context context, Handler handler) {
this.handler = handler;
View layout = LayoutInflater.from(context).inflate(R.layout.custom_toast_succ, null, false);
toast_content = (TextView) layout.findViewById(R.id.tvToastContent);
if (toast == null) {
toast = new Toast(context);
}
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
}
/**
* @param text 要显示的内容
* @param duration 显示的时间长
* 根据LENGTH_MAX进行判断
* 如果不匹配,进行系统显示
* 如果匹配,永久显示,直到调用hide()
*/
public void show(String text, int duration) {
time = new TimeCount(duration, 1000);//1000是消失渐变时间
toast_content.setText(text);
if (canceled) {
time.start();
canceled = false;
showUntilCancel();
}
}
/**
* 隐藏Toast
*/
public void hide() {
if (toast != null) {
toast.cancel();
}
canceled = true;
}
private void showUntilCancel() {
if (canceled) {
return;
}
toast.show();
handler.postDelayed(new Runnable() {
public void run() {
showUntilCancel();
}
}, 3000);
}
/**
* 计时器
*/
class TimeCount extends CountDownTimer {
public TimeCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval); // 总时长,计时的时间间隔
}
@Override
public void onFinish() { // 计时完毕时触发
hide();
}
@Override
public void onTick(long millisUntilFinished) { // 计时过程显示
}
}
}
注解:new TimeCount(duration, 1000);//1000是消失渐变时间
4、custom_toast_succ.xml是布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_custom_parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="35dp"
android:background="@drawable/bg_img_toast_succ">
<TextView
android:id="@+id/tvToastContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#FFFFFF" />
</RelativeLayout>
</LinearLayout>
5、背景图;
结尾:
总体上使用效果不错的。