软件开发/Android/Singleton

来自RoomChat
跳转至: 导航搜索

Android 单例对象往往需要传递Context对象,所以先在 Application 对象创建一个实例引用:

   public class App extends Application {
      private static App instance;
      public static App get() { return instance; }
   
      @Override
      public void onCreate() {
         super.onCreate();
         instance = this;
      }
   }

然后用 enum 创建单例对象:

   public enum SingleUtil {
       INSTANCE;
       private Context context = App.getInstance();
       public Drawable drawableFromID(int id) {
           return context.getResources().getDrawable(id);
       }
   }

使用:

   Drawable drawable = SingleUtil.INSTANCE.drawableFromID(android.R.drawable.ic_media_play);