教你如何获取全局Context

   public class MyApplication extends Application {
        public static Context mContext;
        @Override
        public void onCreate() {
            super.onCreate();
            mContext = this;//获取本类对象
        }
    }
    
    public class ToastUtils {
    private static Toast toast;//单例toast

    public static void showToast( String text) {
        if (toast == null) {
            toast = Toast.makeText(MyApplication.mContext, text, Toast.LENGTH_SHORT);
        } 

            toast.setText(text);

    toast.show();

  }

要让MyApplicaton这个类生效,就必须为其注册。我们需要在AndroidManifest.xml中的

你可能感兴趣的:(安卓开发)