android 自定义Toast 显示时长 样式
吐司(Toast),在Android开发中主要是提示功能,但是有时候系统原生的不能满足我们的需求,只用自定义才能解决,下面是一种自定义的方式:
1、首先是布局文件toast.xml(就是你Toast显示的样式)
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="80dp"
android:layout_height="30dp"
android:padding="10dp"
android:gravity="center"
android:background="@drawable/toaststyle"
android:orientation="horizontal">
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/imageView"/>
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:shadowColor="#bbfcd603"
android:shadowRadius="2.75"
android:textColor="#ffffff"
/>
2、style样式 toaststyle.xml
<?xml version="1.0" encoding="utf-8"?>
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"/>
3、Toast工具类(这才是核心)
public class ShowToastUtil {
private static TextView mTextView;
private static ImageView mImageView;
public static void showToast(Context context, String message,int cnt) {
final Timer timer = new Timer();
//加载Toast布局
View toastRoot = LayoutInflater.from(context).inflate(R.layout.toast, null);
//初始化布局控件
mTextView = (TextView) toastRoot.findViewById(R.id.message);
mImageView = (ImageView) toastRoot.findViewById(R.id.imageView);
//为控件设置属性
mTextView.setText(message);
mImageView.setImageResource(R.mipmap.ic_launcher);
//Toast的初始化
final Toast toastStart = new Toast(context);
//获取屏幕高度
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int height = wm.getDefaultDisplay().getHeight();
//Toast的Y坐标是屏幕高度的1/3,不会出现不适配的问题
toastStart.setGravity(Gravity.TOP, 0, height / 3);
toastStart.setDuration(Toast.LENGTH_LONG);
toastStart.setView(toastRoot);
timer.schedule(new TimerTask() {
@Override
public void run() {
toastStart.show();
}
}, 0, 3000); //Toast long默认显示的是3000毫秒,所以设置成3000
new Timer().schedule(new TimerTask() {
@Override
public void run() {
toastStart.cancel();
timer.cancel();
}
}, cnt );
}
4、在调用的的地方设置显示时长
findViewById(R.id.tv).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShowToastUtil.showToast(MainActivity.this,"第一个自定义的Toast",30000);
}
});
更多相关文章
- Android显示图片崩溃的解决办法
- Android(安卓)- UI(User Interface)的基本设计
- android实现下拉框和输入框结合
- Android(安卓)ViewGroup中addView方法使用
- android 点击获取验证码显示倒计时并不可用
- Android(安卓)应用第一次运行时,引导页面的设置方法(只让程序Aciti
- 软键盘隐藏和显示问题.
- Android(安卓)去除“Viewing full screen”弹窗
- Android(安卓)7.0拍照后保存到手机的指定目录并返回显示