可以看到,这里我快速连续点击了五次按钮,Toast就触发了五次。这样的体验其实是不好的,因为也许用户是手抖了一下多点了几次,导致Toast就长时间关闭不掉了。又或者我们其实已在进行其他操作了,应该弹出新的Toast提示,而上一个Toast却还没显示结束。
改进方式
public class Util {
private static Toast toast;
public static void showToast(Context context,
String content) {
if (toast == null) {
toast = Toast.makeText(context,
content,
Toast.LENGTH_SHORT);
} else {
toast.setText(content);
}
toast.show();
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="提交"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="自定义toast"/>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textview_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是标题"/>
<ImageView
android:id="@+id/imageview_toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/textview_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是内容"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mButton1;
private Button mButton2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1= (Button) findViewById(R.id.button1);
mButton2= (Button) findViewById(R.id.button2);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Toast toast= Toast.makeText(getApplicationContext(), "我是Toast", Toast.LENGTH_LONG);
Spanned spanned= Html.fromHtml("我<img src=''/>是<img src=''/>一个<font color='#ff0000'>toas</font>", new Html.ImageGetter() {
@Override
public Drawable getDrawable(String source) {
Drawable drawable =getResources().getDrawable(R.mipmap.ic_launcher);
drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
return drawable;
}
},null);
toast.setText(spanned);
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER|Gravity.BOTTOM,0,0);
toast.show();
break;
case R.id.button2:
Toast toast1=Toast.makeText(getApplicationContext(),"我是Toast", Toast.LENGTH_LONG);
LayoutInflater inflater=getLayoutInflater();
View view=inflater.inflate(R.layout.activity_toast,null);
toast1.setView(view);
toast1.setDuration(Toast.LENGTH_LONG);
toast1.show();
break;
default:
break;
}
}