1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.layoutlib.bridge.util; 18 19import com.android.annotations.NonNull; 20import com.android.resources.ResourceType; 21import com.android.util.Pair; 22 23import android.util.SparseArray; 24 25import java.util.HashMap; 26import java.util.Map; 27 28public class DynamicIdMap { 29 30 private final Map<Pair<ResourceType, String>, Integer> mDynamicIds = new HashMap<Pair<ResourceType, String>, Integer>(); 31 private final SparseArray<Pair<ResourceType, String>> mRevDynamicIds = new SparseArray<Pair<ResourceType, String>>(); 32 private int mDynamicSeed; 33 34 public DynamicIdMap(int seed) { 35 mDynamicSeed = seed; 36 } 37 38 public void reset(int seed) { 39 mDynamicIds.clear(); 40 mRevDynamicIds.clear(); 41 mDynamicSeed = seed; 42 } 43 44 /** 45 * Returns a dynamic integer for the given resource type/name, creating it if it doesn't 46 * already exist. 47 * 48 * @param type the type of the resource 49 * @param name the name of the resource 50 * @return an integer. 51 */ 52 @NonNull 53 public Integer getId(ResourceType type, String name) { 54 return getId(Pair.of(type, name)); 55 } 56 57 /** 58 * Returns a dynamic integer for the given resource type/name, creating it if it doesn't 59 * already exist. 60 * 61 * @param resource the type/name of the resource 62 * @return an integer. 63 */ 64 @NonNull 65 public Integer getId(Pair<ResourceType, String> resource) { 66 Integer value = mDynamicIds.get(resource); 67 if (value == null) { 68 value = ++mDynamicSeed; 69 mDynamicIds.put(resource, value); 70 mRevDynamicIds.put(value, resource); 71 } 72 73 return value; 74 } 75 76 public Pair<ResourceType, String> resolveId(int id) { 77 return mRevDynamicIds.get(id); 78 } 79} 80