Search code examples
javaandroidtoastandroid-toast

Android - Custom Toast Class


I am trying to create a class that it´s supossed to show a toast every time that an object of this class is instaciated. I want to do this so that I don´t have the same toast code repeated in every activity.

public class Toast extends android.widget.Toast {
    String toast_text;
    Context toast_context;

    public Toast(String toast_text, Context toast_context) {
        this.toast_text = toast_text;
        this.toast_context = toast_context;

        Toast toast = android.widget.Toast.makeText(this.toast_context.this, this.toast_text, Toast.LENGTH_LONG);
        ViewGroup view = (ViewGroup) toast.getView();
        view.setBackgroundResource(R.drawable.background_global);

        TextView messageTextView = (TextView) view.getChildAt(0);
        messageTextView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        messageTextView.setTextSize(35);

        Typeface face_font = Typeface.createFromAsset(getAssets(), "res/font/aldrich.ttf");
        messageTextView.setTypeface(face_font);
        messageTextView.setTextColor(Color.CYAN);

        toast.show();
    }
}

These are the following erros:

On the constructor: "There is no default constructor available in "android.widget.toast"; On the first error: " ')' expected"; On the second error: "Cannot resolve method "getAssets" ".


Solution

  • Use toast_context that you receive through constructor to create toast and access asset

    Toast toast = android.widget.Toast.makeText(toast_context, toast_text, Toast.LENGTH_LONG);
    

    Typeface face_font = Typeface.createFromAsset(toast_context.getAssets(), "res/font/aldrich.ttf");
    

    Beside this, You should use other name than Toast to create custom toast

    class MyToast extends android.widget.Toast {
    
        public MyToast(String toast_text, Context toast_context) {
            super(toast_context);
    
            ...
    
        }
    }