How to centralize a custom toast creation

社会主义新天地 提交于 2019-12-12 14:06:39

问题


in my application i use a custom toast in almost all the activity. To create the custom toast i have the following method :

private void getCustomToast(String message)
{
    LayoutInflater li   = getLayoutInflater();
    View toastlayout    = li.inflate(R.layout.toast_error, (ViewGroup)findViewById(R.id.toast_layout));
    TextView text       = (TextView) toastlayout.findViewById(R.id.toast_text);
    text.setText(message);

    Toast toast = new Toast(this);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(toastlayout);
    toast.show();
}

It works fine but for each activity I need to duplicate this method, not really respectfull of the DRY principle ...

How can i make a static class (for example) in which i have a method which gonna fire the custom toast on the current activity ?

Thanks


回答1:


You should make a custom abstract Activity that contains the toast method, and then extend that for your application's activities:

public abstract class ToastActivity extends Activity {

    protected void getCustomToast(String message)
    {
        LayoutInflater li = getLayoutInflater();
        View toastlayout  = li.inflate(
                R.layout.toast_error, 
                (ViewGroup) findViewById(R.id.toast_layout));

        TextView text = (TextView) toastlayout.findViewById(R.id.toast_text);
        text.setText(message);

        Toast toast = new Toast(this);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(toastlayout);
        toast.show();
    }

}



回答2:


I want to say you can create a [static] class which will accept a Context object. Then use:

Toast toast = Toast.makeText(context, text, duration).show();

So in your static class:

public static class Utility
{
    public static void toast(Context context, String msg)
         {
              Toast toast = Toast.makeText(context, msg, Toast.DURATION_LONG).show();

         }

}

Or something like that



来源:https://stackoverflow.com/questions/7041475/how-to-centralize-a-custom-toast-creation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!