Guest User

Untitled

a guest
Dec 17th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. /**
  2. * 用于缓存View使用
  3. *
  4. * @author legendmohe
  5. */
  6. public final class ViewCache {
  7.  
  8. private static final String TAG = "ViewCache";
  9.  
  10. private final ExecutorService service;
  11. private final SparseArray<List<View>> mStack;
  12.  
  13. private ViewCache() {
  14. service = Executors.newSingleThreadExecutor();
  15. mStack = new SparseArray<>(2);
  16. }
  17.  
  18. private static class LazyHolder {
  19. private static final ViewCache INSTANCE = new ViewCache();
  20. }
  21.  
  22. public static ViewCache getInstance() {
  23. return LazyHolder.INSTANCE;
  24. }
  25.  
  26. /**
  27. * 获取缓存View
  28. *
  29. * @return View
  30. */
  31. @Nullable
  32. public synchronized View popAndAquire(Configuration configuration) {
  33. List<View> views = mStack.get(configuration.orientation);
  34. push(configuration);
  35.  
  36. if (views != null && views.size() > 0) {
  37. return views.remove(views.size() - 1);
  38. }
  39. return null;
  40. }
  41.  
  42. /**
  43. * 在其他线程进行View初始化
  44. *
  45. * @param configuration Configuration
  46. */
  47. private void push(final Configuration configuration) {
  48. service.execute(new Runnable() {
  49. @Override
  50. public void run() {
  51. if (Looper.myLooper() == null) {
  52. Looper.prepare();
  53. }
  54.  
  55. long startTime = SystemClock.uptimeMillis();
  56. View view = View.inflate(activity, R.layout.your_layout_id, null);
  57. long endTime = SystemClock.uptimeMillis() - startTime;
  58.  
  59.  
  60. List<View> views = mStack.get(configuration.orientation);
  61. if (views == null) {
  62. views = new ArrayList<>();
  63. mStack.put(configuration.orientation, views);
  64. }
  65.  
  66. views.add(view);
  67. Log.i(TAG, "push finished, inflate time=" + endTime + " size=" + views.size());
  68. }
  69. });
  70. }
  71.  
  72. public void push(Configuration configuration, boolean onlyNotExist) {
  73. if (onlyNotExist && isInstanceExisted(configuration)) {
  74. return;
  75. }
  76. push(configuration);
  77. }
  78.  
  79. public synchronized void push(Configuration configuration, int maxStackSize) {
  80. if (maxStackSize <= 0) {
  81. return;
  82. }
  83.  
  84. List<View> views = mStack.get(configuration.orientation);
  85. if (views != null && views.size() >= maxStackSize) {
  86. return;
  87. }
  88.  
  89. push(configuration);
  90. }
  91.  
  92. public synchronized boolean isInstanceExisted(Configuration configuration) {
  93. if (configuration == null) {
  94. return false;
  95. }
  96. List<View> views = mStack.get(configuration.orientation);
  97. return views != null && views.size() != 0;
  98. }
  99. }
Add Comment
Please, Sign In to add comment