Toast提供了一个很方便的与用户交互的反馈方式。如下图:
Toast大致分一下几种:
1>普通Toast
private void normalToast() { Toast.makeText(context, "normalToast", Toast.LENGTH_SHORT).show(); }
2>带图片的Toast
1 private void picToast() { 2 Toast toast = Toast.makeText(context, "picToast", Toast.LENGTH_SHORT); 3 toast.setGravity(Gravity.CENTER, -50, 50); 4 LinearLayout view = (LinearLayout) toast.getView(); 5 view.setBackgroundColor(0x2f78E100); 6 ImageView imageView = new ImageView(context); 7 imageView.setImageResource(R.drawable.ic_launcher); 8 view.addView(imageView); 9 toast.setView(view); 10 toast.show(); 11 }
执行效果:
3.自定义Toast
自定义Toast需要我们自己定义一个布局文件来定义Toast的外观
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:background="#f0CA8F00" 6 android:orientation="vertical" > 7 8 <ImageView 9 android:layout_gravity="center" 10 android:layout_width="80dip" 11 android:layout_height="40dip" 12 android:src="@drawable/haha" /> 13 14 <TextView 15 android:id="@+id/text" 16 android:layout_gravity="center" 17 android:gravity="center" 18 android:layout_width="200dip" 19 android:layout_height="50dip" 20 android:textColor="#F6F6F6" /> 21 22 </LinearLayout>
1 private void customToast() { 2 LayoutInflater inflater = getLayoutInflater(); 3 View layout = inflater.inflate(R.layout.toast_layout, null); 4 layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 5 LayoutParams.WRAP_CONTENT)); 6 TextView textview = (TextView) layout.findViewById(R.id.text); 7 textview.setText("Custom Toast"); 8 Toast toast = new Toast(context); 9 // toast.setMargin(10, 30); 10 toast.setView(layout); 11 toast.show(); 12 }
执行效果:
注:Toast操作也是一种UI操作,所以如果我们要在别的线程中用Toast会出现错误,我们可以用handler.post方法解决,如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void runInOtherThread() { 2 new Thread(new Runnable() { 3 4 @Override 5 public void run() { 6 handler.post(new Runnable() { 7 8 @Override 9 public void run() { 10 Toast.makeText(context, "runInOtherThread", 11 Toast.LENGTH_SHORT).show(); 12 } 13 }); 14 15 } 16 }).start(); 17 }