Android Toast工具类

AndroidToast大约 1943 字

单例Toast

public class ToastUtil {
    private static Toast toast;
    public static void showToast(String text){
        if(toast==null){
            //创建toast
            toast = Toast.makeText(GooglePlayApp.context,text,Toast.LENGTH_SHORT);
        }
        //如果吐司已经创建,那么直接更改吐司的文本即可
        toast.setText(text);
        //最后显示
        toast.show();
    }
}

更改背景为圆角的Toast

public class ToastUtil {
    private static Toast    toast;
    private static TextView sTextView;
    public static void show(String text) {
        if (toast == null) {
            View toastRoot = LayoutInflater.from(IMApp.mContext).inflate(R.layout.im_toast, null);
            sTextView = (TextView) toastRoot.findViewById(R.id.im_toast_tv);
            toast = new Toast(IMApp.mContext);
            toast.setView(toastRoot);
        }
        sTextView.setText(text);
        toast.show();
    }
}

Toast的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/im_toast_bg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/im_shape_toast">
    <TextView
        android:id="@+id/im_toast_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:layout_marginTop="10dp"
        android:textColor="@android:color/white"/>
</LinearLayout>

定义Toast为圆角的shape

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <!-- 填充的颜色 -->
    <solid android:color="#11cc6e"/>
    <!-- android:radius 弧形的半径 -->
    <corners android:radius="20dip"/>
</shape>
阅读 774 · 发布于 2019-04-14

————        END        ————

扫描下方二维码关注公众号和小程序↓↓↓

昵称:
随便看看换一批