小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
Android 自定义提示
Android自带的提示是Toast,无论是开发调试的提示还是对用户的提示,都是很方便的就能写入,但Toast的提示对用户来说实在简单,简单也不要紧,主要是有时候页面颜色不搭配的情况,就看不清楚了。这篇文章讲解如何实现自定义的Toast。
Toast队列
大家有没有遇到过这样的现象,就是一瞬间执行多个Toast的时候,系统会依次的将Toast显示出来,这是因为Toast.makeText内部其实new了很多个Toast,而系统将这些Toast采用队列的方式,依次显示,可以查看运行例1的代码证明。这种并不是我们想要的情况,因为我们想要即时的给出提示,那么我们就只能使用单个Toast,然后去setText更新内容,这也就是例2的代码。
例1 - 循环提示
for (int i = 0; i < 10; i++) {
Toast.makeText(this, "toast提示:" +i,Toast.LENGTH_SHORT).show();
}
例2 - 只提示最新的
for (int i = 0; i < 10; i++) {
if (toast == null)
toast = Toast.makeText(this, "toast提示:" + i, Toast.LENGTH_SHORT);
else {
toast.setText("toast提示:" + i);
toast.setDuration(Toast.LENGTH_SHORT);
}
toast.show();
}
Toast自定义界面
我们平时使用Toast,仅仅需要一行代码就可以搞定。
Toast.makeText(this,"toast提示", Toast.LENGTH_LONG).show();
但如果想自定义界面怎么办呢,重点看看下面几个Toast的方法。
-
setGravity: 设置通知应显示在屏幕上的位置。
-
setView: 设置视图
-
setDuration:设置显示视图的时间。
-
show: 显示
有了这几个属性就好办了,我们先写好Layout文件,然后将layout文件转为View,然后通过setView将View设置进去即可。我们来尝试一下。
先写一个layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/shape_round_white_border"
android:orientation="vertical">
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:padding="20dp"
android:text=""
android:textColor="#ffffff"
android:textSize="20sp" />
</LinearLayout>
shape_round_white_border
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="10dp" />
<solid android:color="#dd000000" />
</shape>
写好的Toast工具类,单例模式即时提示消息。
public class ToastCustom {
private static Handler handler = new Handler(Looper.getMainLooper());
private static Toast mToast; //避免Toast多次频繁弹出
/**
* 自定义的吐司
*/
public static void custom(final View view) {
final Context context = AppCache.getContext();
if (context == null)
return;
handler.post(new Runnable() {
@Override
public void run() {
if (mToast == null) {
mToast = new Toast(AppCache.getContext());
}
mToast.setGravity(Gravity.CENTER, 0, 0);
mToast.setView(view);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.show();
}
});
}
}
使用它
View layout_view = getLayoutInflater().inflate(R.layout.toast_custom, null);
TextView toast_text = layout_view.findViewById(R.id.toast_text);
toast_text.setText("我是Toast提示");
ToastCustom.custom(layout_view);