Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 用于缓存View使用
- *
- * @author legendmohe
- */
- public final class ViewCache {
- private static final String TAG = "ViewCache";
- private final ExecutorService service;
- private final SparseArray<List<View>> mStack;
- private ViewCache() {
- service = Executors.newSingleThreadExecutor();
- mStack = new SparseArray<>(2);
- }
- private static class LazyHolder {
- private static final ViewCache INSTANCE = new ViewCache();
- }
- public static ViewCache getInstance() {
- return LazyHolder.INSTANCE;
- }
- /**
- * 获取缓存View
- *
- * @return View
- */
- @Nullable
- public synchronized View popAndAquire(Configuration configuration) {
- List<View> views = mStack.get(configuration.orientation);
- push(configuration);
- if (views != null && views.size() > 0) {
- return views.remove(views.size() - 1);
- }
- return null;
- }
- /**
- * 在其他线程进行View初始化
- *
- * @param configuration Configuration
- */
- private void push(final Configuration configuration) {
- service.execute(new Runnable() {
- @Override
- public void run() {
- if (Looper.myLooper() == null) {
- Looper.prepare();
- }
- long startTime = SystemClock.uptimeMillis();
- View view = View.inflate(activity, R.layout.your_layout_id, null);
- long endTime = SystemClock.uptimeMillis() - startTime;
- List<View> views = mStack.get(configuration.orientation);
- if (views == null) {
- views = new ArrayList<>();
- mStack.put(configuration.orientation, views);
- }
- views.add(view);
- Log.i(TAG, "push finished, inflate time=" + endTime + " size=" + views.size());
- }
- });
- }
- public void push(Configuration configuration, boolean onlyNotExist) {
- if (onlyNotExist && isInstanceExisted(configuration)) {
- return;
- }
- push(configuration);
- }
- public synchronized void push(Configuration configuration, int maxStackSize) {
- if (maxStackSize <= 0) {
- return;
- }
- List<View> views = mStack.get(configuration.orientation);
- if (views != null && views.size() >= maxStackSize) {
- return;
- }
- push(configuration);
- }
- public synchronized boolean isInstanceExisted(Configuration configuration) {
- if (configuration == null) {
- return false;
- }
- List<View> views = mStack.get(configuration.orientation);
- return views != null && views.size() != 0;
- }
- }
Add Comment
Please, Sign In to add comment