代码之家  ›  专栏  ›  技术社区  ›  Miaoulis Nikos

如何使用公共静态类创建自定义Toast

  •  0
  • Miaoulis Nikos  · 技术社区  · 8 年前

    我创建了以下内容,以控制多个toast消息的情况

    public class ExtraUtils {
    
    public static Activity MyActivity;
    public static LayoutInflater mInflater;
    
    public static void MyToast(View view,int ToastCase) 
    {
        Context context=MyActivity.getApplicationContext();
        mInflater = LayoutInflater.from(context);
    
        View customToastroot =mInflater.inflate(R.layout.custom_toast, null);
        Toast customtoast=new Toast(context);
        TextView text = (TextView) customToastroot.findViewById(R.id.txtToast);
        // Set the Text to show in TextView
        switch(ToastCase)
        {
            case 1:
                text.setText("You cannot Select this Again");
                break;
            case 2:
                text.setText("Oops Something went wrong");
                break;
        }
    }
    }
    

    我把它叫做ExtraUtils。MyToast(视图,1),但在

    Context context=MyActivity.getApplicationContext();
    
    2 回复  |  直到 8 年前
        1
  •  2
  •   gprathour davidbuzatto    5 年前

    改变

    Context context = MyActivity.getApplicationContext();

    Context context = MyActivity.this;

    编辑

    对不起,我以为你正在MyActivity本身中编写代码。你需要做的是,

    public static void MyToast(View view,int ToastCase, Context context)
    

    在MyActivity中,

     ExtraUtils.MyToast(view, 1, MyActivity.this)
    
        2
  •  1
  •   Poovizhirajan N    8 年前

    你的代码无法工作!!! 我的活动 不是 已初始化 ...

    发送参数内的内容

    public static void MyToast(Content context,View view,int ToastCase) {
        // Context context=MyActivity.getApplicationContext();
        mInflater = LayoutInflater.from(context);
        View customToastroot =mInflater.inflate(R.layout.custom_toast, null);
        Toast customtoast=new Toast(context);
        TextView text = (TextView) customToastroot.findViewById(R.id.txtToast);
        // Set the Text to show in TextView
        switch(ToastCase) {
            case 1:
                text.setText("You cannot Select this Again");
                break;
            case 2:
                text.setText("Oops Something went wrong");
                break;
        }
       //...Write Code for display toast
    }