系统自带的Toast已能满足绝大部分需求,然鹅在显示时长方面如果有一些要求的话就需要简单进行自定义Toast处理:
首先一个简单的Toast工具类:
public class ToastUtils { private static Toast toast; /** * 短时间显示Toast * * @param context * @param message */ public static void showShort(Context context, String message) { if (TextUtils.isEmpty(message)) { return; } LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // 自定义布局 View view = inflater.inflate(R.layout.toast_center, null); // 自定义toast文本 TextView mTextView = (TextView) view.findViewById(R.id.toast_msg); mTextView.setText(message + ""); if (toast == null) { toast = new Toast(context); } toast.setView(view); toast.setDuration(Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM, 0, 200); toast.show(); canCel(toast); } private static void canCel(final Toast toast) { canCel(toast, 900); } private static void canCel(final Toast toast, int time) { Observable.timer(time, TimeUnit.MILLISECONDS).subscribe(new Consumer<Long>() { @Override public void accept(Long aLong) throws Exception { if (toast != null) toast.cancel(); } }); } }
附上布局代码:
toast_center.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:layout_centerHorizontal="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/rl_bg" > <TextView android:text="haha" android:id="@+id/toast_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginBottom="5dp" android:textColor="#ffffff" android:textSize="16sp" /> </RelativeLayout> </RelativeLayout>
drawable文件:rl_bg.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <corners android:radius="5dp"></corners> <solid android:color="#99222222"></solid> </shape>