【Android】自定义Toast样式

自定义Toast样式

原生Toast样式

自定义Toast样式

创建样式

所谓自定义一个Toast就是建立一个布局文件,然后使用一个view容器承载,然后显示出来。Toast毕竟只是起到一个提示作用,不必要放太多控件去填充,反而会显得内容很拥挤,一般一个标题,一张图片,一段简短文字即可。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/white_radius_10">
    <LinearLayout
        android:layout_width="120dp"
        android:layout_height="100dp"
        android:gravity="center"
        android:orientation="vertical"
        android:layout_gravity="center">

        <ImageView
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:src="@drawable/icon_error" />

        <TextView
            android:id="@+id/ErrorTips"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:text="密码错误,请重试!"
            android:textColor="#099A9F"
            android:textSize="15sp"
            android:ellipsize="end"/>
    </LinearLayout>
</FrameLayout>

封装

因为我们在开发中需要频繁使用Toast,所以使用一个类将其封装起来,复用其功能,增强代码可读性,可行性。根据自己的开发需求,可以向外暴露修改内容,图片,颜色,文字大小等方法,由于Toast内附控件较少,就可以直接将其控件ID和布局文件定义为常量引用。

public class ToastFormat {
    private Context context;
    private TextView tipsText;
    private Toast toast = null;
    private static final int ContentID = R.id.ErrorTips;
    private static final int LayoutID = R.layout.passworderror;
    public ToastFormat(Context context){
        this.context = context;
    }
    public void InitToast(){
        if (toast == null) {
            toast = new Toast(context);
            View view = LayoutInflater.from(context).inflate(LayoutID, null, false);
            tipsText = view.findViewById(ContentID);
            toast.setView(view);
        }
    }
    public void setGravity(int gravity){
        toast.setGravity(gravity, 0, 0);
    }
    public void setText(String tips){
        tipsText.setText(tips);
    }
    public void show(){
        toast.show();
    }
    public void setShowTime(int time){
        toast.setDuration(time);
    }
    public void setTextColor(int color){
        tipsText.setTextColor(context.getResources().getColor(color));
    }
    public void setTextSize(float size){
        tipsText.setTextSize(size);
    }
}

引用

定义对象

private ToastFormat format;

初始化

format = new ToastFormat(MainActivity.this);
format.InitToast();

设置显示文字内容

format.setText("自定义Toast");

最后显示 Toast

format.show();

猜你喜欢

转载自blog.csdn.net/News53231323/article/details/123968086