Toast customization
Toast is a simple generic class (so by default derived from object)
It create a view using WindowManager with an overlay feature , after inflating view and setting gravity , pading , offsets... it calls addView , then quickly notify AccessibilityManager about events as below (Code extracted from Android SDK)
AccessibilityEvent event = AccessibilityEvent.obtain(
AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED);
event.setClassName(getClass().getName());
event.setPackageName(mView.getContext().getPackageName());
mView.dispatchPopulateAccessibilityEvent(event);
accessibilityManager.sendAccessibilityEvent(event);
so for customizing a Toaster developers have two solutions:
1) Do the same process above as done by original SDK Toast(creating an Overlay window using WindowManager services)
2)subclass Toast class as below for a very simple basic case:
public class ToastPlus extends Toast {
ToastPlus(Context context){
super(context);
}
public static void showToastPlus(Context context,String text,Drawable icon,int duration){
ToastPlus toast = new ToastPlus(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View customView =inflater.inflate(R.layout.toastplus, null);
toast.setView(customView);
TextView tv =(TextView)customView.findViewById(R.id.textView1);
ImageView iv = (ImageView)customView.findViewById(R.id.imageView1);
tv.setText(text);
iv.setImageDrawable(icon);
//toast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL,0, 0);
toast.setDuration(duration);
toast.show();
}
}
////Custom layout toastplus.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="5px"
android:padding="10dp"
android:layout_gravity="center_horizontal">
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/toastborder">
<ImageView
android:id="@+id/imageView1"
android:src="@drawable/movetosdcard"
android:layout_width="50dp"
android:layout_height="50dp"/>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dp"
android:text="Android Tutorial Custom Toast"
android:textColor="#fff"
android:textSize="16dp"
android:layout_gravity="center_vertical"/>
</LinearLayout>
</LinearLayout>
Then Somewhere in your codes you call:
ToastPlus.showToastPlus(context,text,icon ,Toast.LENGTH_SHORT);//icon=drawable