android Toast 重复显示问题

我们知道,android,每次创建toast的时候,会放到系统的一个队列,然后依次显示,直到最后一个显示完全,这样有时候会导致,用户重复点击,导致toast显示很长时间,用户体验不好,如果只需要显示最新的toast,实现如下:

static Toast result;
public static Toast makeText(int icon,Context context,CharSequence text){
    try {
        if(result != null){
        result.cancel();
        result = null;
    }
        result = new Toast(context);
        LayoutInflater inflate = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.list_item_define_toast, null);
        TextView tv = (TextView)v.findViewById(R.id.id_tv);
        tv.setText(text);
        ImageView iv = (ImageView)v.findViewById(R.id.iv_iv_icon);
        iv.setImageResource(icon);
        result.setView(v);
        result.setDuration(0);
        result.setGravity(Gravity.TOP, 0, 0);
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return Toast.makeText(context, text, 0);
}

自定义list_item_define_toast.xml布局文件代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent" >
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:background="@drawable/soild_black_rs_5_storke"
        >
        <LinearLayout 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="horizontal"
            android:layout_marginLeft="15dp"
            android:layout_marginRight="15dp"
            >
            
            
            <ImageView
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:id="@+id/iv_iv_icon"
            android:layout_marginRight="6dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_gravity="center_vertical"
            android:src="@drawable/refresh_success"
            />
            
            <TextView 
                android:layout_marginBottom="10dp"
                android:layout_marginTop="10dp"
                android:layout_gravity="center_vertical"
            android:id="@+id/id_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="@dimen/jh_size_text_normal"
            android:text="我是一个Toast"
            />
        
        
        
        </LinearLayout>
        
        
 </RelativeLayout>
</RelativeLayout>


你可能感兴趣的:(android Toast 重复显示问题)