Toast通知十分方便,比起Dialog,不受Activity生命周期的影响(当Activity finish()之后,Toast依然可以存在)。
Android自带组件的风格都很挫,跟iOS没法比,直接拿来用的情况几乎没有,都需要自定义。包括这个Toast。
step1、自定义Toast要用的xml文件
step2、new Toast()
step3、设置新建的toast的属性,Toast已经有很多设置可以设置,十分方便。
xml文件:
<? 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" >
<LinearLayout
android:layout_width= "450dp"
android:layout_height= "50dp"
android:background= "#000000"
android:orientation= "vertical"
>
<TextView
android:id= "@+id/my_txt"
android:layout_gravity= "center"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:textSize= "30sp"
android:text ="helloworld"
android:textColor= "#ffffff"
/>
</LinearLayout >
</ LinearLayout>
新建Toast,设置属性:
public class ShowUtils{
public static Toast myToast;
public static void ShowToast(Context context, String str, int duration){
if( myToast == null){
myToast = new Toast(context);
}
View view = View. inflate(context, R.layout.toast_layout , null);
TextView text = (TextView)view.findViewById(R.id.my_txt );
text.setText(str);
myToast.setDuration(duration);
myToast.setGravity(Gravity. CENTER, 0, 10);
myToast.setView(view);
myToast.show();
}
}
使用:
ShowUtils. ShowToast(MainActivity. this, "helloworld" ,
1000);
效果:
ctrlz presents!