效果:
步骤:
1写Toast布局
我们写一句话和一个图
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" /> <ImageView android:layout_width="60dp" android:layout_height="60dp" android:layout_gravity="center" android:src="@drawable/toast" /> </LinearLayout>
2。MainActivity中创建Toast,设置Toast的view为我们刚写布局
关键代码
protected void myToast(String msg) { //加载View对象 LayoutInflater inflater=getLayoutInflater(); View view = inflater.inflate(R.layout.mytoast, null); TextView tv=(TextView) view.findViewById(R.id.tv); tv.setText(msg); Toast toast=new Toast(this); //设置位置 toast.setGravity(Gravity.CENTER, 0, 80); //设置时长 //toast.setDuration(1000); //给Toast设置view toast.setView(view); toast.show(); }
还可以通过WindowManager实现自定义Toast