自定义Toast

来源:互联网 发布:ubuntu设置ip自动获取 编辑:程序博客网 时间:2024/06/06 01:54

系统自带的Toast会非常的难看,没有一些自己样式,只可以设置文字和显示位置。企业项目中一般都会自定义Toast。下面就写一份自己经常用的自定义Toast作为模板。

一. 首先先写一个布局文件。

 设计Toast的布局,Toast好不好看,全在这个布局文件里面体现。已过一般Toast都是简洁美。不要太花哨。

toast_custom.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical" android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:background="@drawable/scale_toast_bg"    android:padding="@dimen/unit10"    android:gravity="center">    <TextView        android:id="@+id/toast_text"        android:layout_width="@dimen/unit180"        android:layout_height="@dimen/unit60"        android:layout_gravity="center"        android:gravity="center"        android:textSize="@dimen/font18"        android:textColor="#ffffff"        /></LinearLayout>
我在文件中只放了一个TextView,主要是给整个Toast加了一个边框,你还可以防止一个ImageView等。

下面是布局文件中用到的scale_toast_bg.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <!-- 填充颜色 -->    <solid android:color="#BE15140F"></solid>    <!-- 线的宽度,颜色灰色 -->    <stroke android:width="3dp" android:color="#B16C17"></stroke>    <!-- 矩形的圆角半径 -->    <corners android:radius="@dimen/unit5" /></shape>
接下来就开始自定义Toast类了

MyToast.java

public class MyToast extends Toast {    private static View view;    public MyToast(Context context) {        super(context);    }    public static MyToast makeText(Context context, CharSequence text, int duration) {        MyToast result = new MyToast(context);        //获取LayoutInflater对象        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        //由layout文件创建一个View对象        view = inflater.inflate(R.layout.toast_costom, null);        //实例化ImageView和TextView对象        TextView textView = (TextView) view.findViewById(R.id.toast_text);        textView.setText(text);        result.setView(view);        result.setGravity(Gravity.CENTER, 0, 0);        result.setDuration(duration);        return result;    }    @Override    public void setText(CharSequence s) {//        super.setText(resId);        if (view == null) {            throw new RuntimeException("This Toast was not created with Toast.makeText()");        }        TextView tv = (TextView) view.findViewById(R.id.toast_text);        if (tv == null) {            throw new RuntimeException("This Toast was not created with Toast.makeText()");        }        tv.setText(s);    }}

然后在用到的地方(一般都会写在基础类中)使用。

private MyToast mToast;public void showToask(String hint) {if (mToast != null){mToast.setText(hint);}else{mToast =  MyToast.makeText(mContext, hint, Toast.LENGTH_SHORT);mToast.setGravity(Gravity.CENTER , 0, 0);}mToast.show();}
上面那种写法是为了避免Toast一直点击一直出现。而是前一次没有消失时第二次出现覆盖掉前一次。

setGravity() 可以设置Toast的显示位置。




0 0
原创粉丝点击