android custom toast of widget development example

  • 2020-05-30 21:01:08
  • OfStack

1. Toast control:

By looking at the source code, it is found that the principle implemented in Toast is to get an LayoutInflater layout manager through the service Context.LAYOUT_INFLATER_SERVICE, thus getting an View object (TextView), and setting the content to display it


public static Toast makeText(Context context, CharSequence text, int duration) {
        Toast result = new Toast(context);
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);

        result.mNextView = v;
        result.mDuration = duration;
        return result;
    }

Define the layout file:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dip"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >
    <ImageView
        android:id="@+id/iv_my_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/notification" />
    <TextView
        android:id="@+id/tv_my_toast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:textSize="18sp"
        android:text="text"
        />
</LinearLayout>

Custom MyToast class:


public class MyToast {
    /**
     *  Displays custom toast 
     * @param context  context 
     * @param iconid  The icon id
     * @param text  Displayed text 
     */
    public static void showToast(Context context,int iconid, String text){
        View view = View.inflate(context, R.layout.my_toast, null);
           TextView tv = (TextView) view.findViewById(R.id.tv_my_toast);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_my_toast);
        iv.setImageResource(iconid);
        tv.setText(text);
        Toast toast = new Toast(context);
        toast.setDuration(0);
        toast.setView(view);
        toast.show();
    }
}


Related articles: