1.自定义显示的视图toast_view.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:gravity="center" android:layout_height="wrap_content" android:background="@drawable/toasts" android:textSize="@dimen/middle_size" android:textColor="@color/common_dialog_text" android:padding="30dip" android:id="@+id/toast_tv"/>
自定义TextView背景toasts.xml(圆角方框)
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="0" android:endColor="@color/operate_success_color" android:startColor="@color/operate_success_color" android:type="linear" /> <corners android:radius="15dp" /> </shape>
2.工具方法显示Toast的自定义视图
/** * 将Toast封装在一个方法中,在其它地方使用时直接输入要弹出的内容即可 * */ public static void ToastMessage(Activity activity, String messages) { //LayoutInflater的作用:对于一个没有被载入或者想要动态载入的界面,都需要LayoutInflater.inflate()来载入,LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化 LayoutInflater inflater = activity.getLayoutInflater();//调用Activity的getLayoutInflater() View view = inflater.inflate(R.layout.toast_view, null); //加載layout下的布局 TextView text = view.findViewById(R.id.toast_tv); text.setText(messages); //toast内容 Toast toast = new Toast(sContext);
toast.setGravity(Gravity.CENTER, 12, 20);//setGravity用来设置Toast显示的位置,相当于xml中的android:gravity或android:layout_gravity(通过该方法定义显示位置,自己根据需要调整就可以了) toast.setDuration(Toast.LENGTH_SHORT);//setDuration方法:设置持续时间,以毫秒为单位。该方法是设置补间动画时间长度的主要方法 toast.setView(view); //添加视图文件 toast.show(); }