Android Toast 工具类

Android About 1,950 words

单例 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>
Views: 4,734 · Posted: 2019-04-14

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

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

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


Today On History
Browsing Refresh