以前用Toast的时候都是直接Toast.makeText,这样直接使用系统自带的Toast,不过并不美观。所以这里我自定义Toast,其实Toast可以假装布局,它有个setView方法。这就是自定义Toast的关键,下面是效果
自定义Toast的布局,mytoast.xml。这里给了根布局一个ID,inflate的时候用的
<?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"
android:id="@+id/my_toast"
android:background="#15cc3e">
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="我的自定义"
android:textSize="16sp"/>
</LinearLayout>
自定义的显示Toast的类。有相关说明。
public class MyToast {
private static Toast toast=null;
private Context context=null;
public MyToast(Context context){
this.context=context;
}
public void show(String string){
//只要显示新的toast就把旧的退出
if(toast!=null)
toast.cancel();
//(Activity)context实现context转换为activity
Activity activity= (Activity) context;
LayoutInflater inflater=activity.getLayoutInflater();
View view=inflater.inflate(R.layout.mytoast, (ViewGroup) activity.findViewById(R.id.my_toast));
//这里还可以加载图片等其他布局
TextView textView= (TextView) view.findViewById(R.id.toast_text);
textView.setText(string);
toast=new Toast(context);
//设置位置
toast.setGravity(Gravity.CENTER,0,0);
//设置显示时间
toast.setDuration(Toast.LENGTH_SHORT);
//设置自定义的布局
toast.setView(view);
toast.show();
ObjectAnimator animator=ObjectAnimator.ofInt(toast,"translationY",toast.getYOffset(),toast.getYOffset()+40);
animator.setDuration(1000);
animator.start();
}
}
利用cancel方法实现了,然后时候都只有一个Toast显示,即新的Toast显示之前把旧的关闭。这样你的Toast可以显示很多东西。但是不建议显示按钮什么的,因为Toast的点击事件是建议的,虽然是可以实现的,但不能跨应用。