当前位置: 代码迷 >> Android >> android应用开发之屡次触发toast的处理
  详细解决方案

android应用开发之屡次触发toast的处理

热度:29   发布时间:2016-04-28 07:48:17.0
android应用开发之多次触发toast的处理

【场景】:当一个比如listview多次点击toast,这时候会出现toast延迟的情况

【处理】:以最后一次toast为准处理

【使用方法】

private ToastUtils mToastUtils;mToastUtils.toast("toast");  //默认的持续的时间是0mToastUtils.toast("toast",1);//可以自定义toast的持续时间

【实现如下】:


ToastUtils.java

import android.content.Context;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.widget.TextView;import android.widget.Toast;public class ToastUtils {	public ToastUtils(Context context) {		ToastMsg.BUILDER.init(context);	}	public enum ToastMsg {		BUILDER;		private Toast toast;		private TextView tv;		private View view;		private void init(Context context) {			view = LayoutInflater.from(context).inflate(R.layout.toast, null);			tv = (TextView) view.findViewById(R.id.tv_toast);			toast = new Toast(context);			toast.setView(view);		}		public void showToast(CharSequence text, int duration) {			if (text.length() != 0) {				tv.setText(text);				toast.setDuration(duration);				toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,						40);				toast.show();			}		}		public void showToast(int id, int duration) {			if (id != 0) {				tv.setText(id);				toast.setDuration(duration);				toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,						40);				toast.show();			}		}	}	public void toast(String text) {		ToastMsg.BUILDER.showToast(text, 0);	}	public void toast(String text, int duration) {		ToastMsg.BUILDER.showToast(text, duration);	}	public void toast(int id) {		ToastMsg.BUILDER.showToast(id, 0);	}}


toast.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:background="@drawable/toast_frame"    android:orientation="horizontal" >    <TextView        android:id="@+id/tv_toast"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_vertical"        android:gravity="left|center"        android:paddingLeft="3dp"        android:paddingRight="3dp"        android:shadowColor="@android:color/white"        android:shadowDx="1.0"        android:shadowDy="1.0"        android:textColor="@android:color/white"        android:textSize="14.0sp" /></LinearLayout>

toast_frame.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android" >    <corners android:radius="4dip" />    <padding        android:bottom="10dip"        android:left="6dip"        android:right="6dip"        android:top="10dip" />    <gradient        android:endColor="#323336"        android:startColor="#323336" />    <stroke        android:width="1dip"        android:color="#ffffff" /></shape>



  相关解决方案