下面列出了android.util.SparseArray#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private SparseArray<List<Group>> getGroupsDataMap() {
SparseArray<List<Group>> idListGroupMap = new SparseArray<>();
SparseArray<Group> groupMapById = getGroupsMap();
Cursor groupMembershipCursor = getCursorFromContentType(new String[]{ID_KEY, MAIN_DATA_KEY}, GroupMembership.CONTENT_ITEM_TYPE);
if (groupMembershipCursor != null) {
while (groupMembershipCursor.moveToNext()) {
int id = groupMembershipCursor.getInt(groupMembershipCursor.getColumnIndex(ID_KEY));
int groupId = groupMembershipCursor.getInt(groupMembershipCursor.getColumnIndex(MAIN_DATA_KEY));
List<Group> currentIdGroupList = idListGroupMap.get(id);
if (currentIdGroupList == null) {
currentIdGroupList = new ArrayList<>();
currentIdGroupList.add(groupMapById.get(groupId));
idListGroupMap.put(id, currentIdGroupList);
} else
currentIdGroupList.add(groupMapById.get(groupId));
}
groupMembershipCursor.close();
}
return idListGroupMap;
}
@NonNull
public Bundle createInstanceState() {
Bundle state = new Bundle();
if (checkedItem != null) {
state.putInt(STATE_CHECKED_ITEM, checkedItem.getItemId());
}
// Store the states of the action views.
SparseArray<ParcelableSparseArray> actionViewStates = new SparseArray<>();
for (int i = 0, size = items.size(); i < size; i++) {
NavigationMenuItem navigationMenuItem = items.get(i);
if (navigationMenuItem instanceof NavigationMenuTextItem) {
MenuItemImpl item = ((NavigationMenuTextItem) navigationMenuItem).getMenuItem();
View actionView = item != null ? item.getActionView() : null;
if (actionView != null) {
ParcelableSparseArray container = new ParcelableSparseArray();
actionView.saveHierarchyState(container);
actionViewStates.put(item.getItemId(), container);
}
}
}
state.putSparseParcelableArray(STATE_ACTION_VIEWS, actionViewStates);
return state;
}
/**
* 常用于ListView|GridView获取ListItem的视图
*
* @param view
* @param id
* @return
*/
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id)
{
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if (viewHolder == null)
{
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if (childView == null)
{
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
@Test
public void testRootHostViewTags() {
final Object tag = new Object();
final SparseArray<Object> tags = new SparseArray<>(1);
tags.put(DUMMY_ID, tag);
final LithoView lithoView =
mountComponent(
mContext,
new InlineLayoutSpec() {
@Override
protected Component onCreateLayout(ComponentContext c) {
return create(c)
.viewTags(tags)
.child(SimpleMountSpecTester.create(c))
.child(SimpleMountSpecTester.create(c))
.build();
}
});
assertThat(lithoView.getTag(DUMMY_ID)).isEqualTo(tag);
}
private <T extends WithLabel> SparseArray<List<T>> getDataMap(Cursor dataCursor, WithLabelCreator<T> creator) {
SparseArray<List<T>> dataSparseArray = new SparseArray<>();
if (dataCursor != null) {
while (dataCursor.moveToNext()) {
int id = dataCursor.getInt(dataCursor.getColumnIndex(ID_KEY));
String data = dataCursor.getString(dataCursor.getColumnIndex(MAIN_DATA_KEY));
int labelId = dataCursor.getInt(dataCursor.getColumnIndex(LABEL_DATA_KEY));
String customLabel = dataCursor.getString(dataCursor.getColumnIndex(CUSTOM_LABEL_DATA_KEY));
T current = creator.create(data, id, labelId, customLabel);
List<T> currentDataList = dataSparseArray.get(id);
if (currentDataList == null) {
currentDataList = new ArrayList<>();
currentDataList.add(current);
dataSparseArray.put(id, currentDataList);
} else currentDataList.add(current);
}
dataCursor.close();
}
return dataSparseArray;
}
static <T> void updateSparseArray(@NonNull SparseArray<T> array, int position, T value,
boolean borderRadius) {
if (borderRadius) {
if (position == BorderDrawable.BORDER_RADIUS_ALL) {
array.put(BorderDrawable.BORDER_RADIUS_ALL, value);
array.put(BorderDrawable.BORDER_TOP_LEFT_RADIUS, value);
array.put(BorderDrawable.BORDER_TOP_RIGHT_RADIUS, value);
array.put(BorderDrawable.BORDER_BOTTOM_LEFT_RADIUS, value);
array.put(BorderDrawable.BORDER_BOTTOM_RIGHT_RADIUS, value);
} else {
array.put(position, value);
}
} else {
if (position == Spacing.ALL) {
array.put(Spacing.ALL, value);
array.put(Spacing.TOP, value);
array.put(Spacing.LEFT, value);
array.put(Spacing.RIGHT, value);
array.put(Spacing.BOTTOM, value);
} else {
array.put(position, value);
}
}
}
/** Move all views remaining in activeViews to scrapViews. */
void scrapActiveViews() {
final View[] activeViews = this.activeViews;
final int[] activeViewTypes = this.activeViewTypes;
final boolean multipleScraps = viewTypeCount > 1;
SparseArray<View> scrapViews = currentScrapViews;
final int count = activeViews.length;
for (int i = count - 1; i >= 0; i--) {
final View victim = activeViews[i];
if (victim != null) {
int whichScrap = activeViewTypes[i];
activeViews[i] = null;
activeViewTypes[i] = -1;
if (!shouldRecycleViewType(whichScrap)) {
continue;
}
if (multipleScraps) {
scrapViews = this.scrapViews[whichScrap];
}
scrapViews.put(i, victim);
victim.setAccessibilityDelegate(null);
}
}
pruneScrapViews();
}
private void storeView(int parentId, int id, View viewRetrieve) {
SparseArray<View> sparseArrayViewsParent = mSparseSparseArrayView.get(parentId);
if (sparseArrayViewsParent == null) {
sparseArrayViewsParent = new SparseArray<View>();
mSparseSparseArrayView.put(parentId, sparseArrayViewsParent);
}
sparseArrayViewsParent.put(id, viewRetrieve);
}
/**
* Move all views remaining in activeViews to scrapViews.
*/
void scrapActiveViews() {
final View[] activeViews = this.activeViews;
final int[] activeViewTypes = this.activeViewTypes;
final boolean multipleScraps = viewTypeCount > 1;
SparseArray<View> scrapViews = currentScrapViews;
final int count = activeViews.length;
for (int i = count - 1; i >= 0; i--) {
final View victim = activeViews[i];
if (victim != null) {
int whichScrap = activeViewTypes[i];
activeViews[i] = null;
activeViewTypes[i] = -1;
if (!shouldRecycleViewType(whichScrap)) {
continue;
}
if (multipleScraps) {
scrapViews = this.scrapViews[whichScrap];
}
scrapViews.put(i, victim);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
victim.setAccessibilityDelegate(null);
}
}
}
pruneScrapViews();
}
@NonNull @Override public SparseArray<T> readFromParcel(@NonNull Parcel source) {
int size = source.readInt();
SparseArray<T> sparseArray = new SparseArray<>(size);
for (int i = 0; i < size; i++) {
sparseArray.put(source.readInt(), itemAdapter.readFromParcel(source));
}
return sparseArray;
}
static final void a(SparseArray sparsearray) {
sparsearray.put(0, new q(0));
q q1 = new q(1);
q q2 = new q(4);
q q3 = new q(5);
q q4 = new q(11);
q q5 = new q(7);
q q6 = new q(8);
q q7 = new q(10);
q q8 = new q(12);
q q9 = new q(13);
q q10 = new q(14);
sparsearray.put(1, q1);
sparsearray.put(4, q2);
sparsearray.put(5, q3);
sparsearray.put(11, q4);
sparsearray.put(12, q8);
sparsearray.put(7, q5);
sparsearray.put(8, q6);
sparsearray.put(10, q7);
sparsearray.put(13, q9);
sparsearray.put(14, q10);
q1.a(q2);
q1.a(q3);
q1.a(q4);
q1.a(q8);
q1.a(q10);
q4.a(q5);
sparsearray.put(2, new q(2));
q q11 = new q(3);
sparsearray.put(3, q11);
q11.a(q9);
q q12 = new q(6);
sparsearray.put(6, q12);
q11.a(q12);
}
public void mapStreamIndex(int stream, int index) {
SparseArray<Float> map = mStreamStepMap.get(stream);
if (null == map) map = new SparseArray<Float>();
try {
float value = getStreamVolume(stream);
map.put(index, value);
} catch (RemoteException re) {
LogUtils.LOGE("AudioFlingerProxy", "Error getting stream volume_3.", re);
}
mStreamStepMap.put(stream, map);
LogUtils.LOGI("AudioFlingerProxy", LogUtils.logSparseArray(mStreamStepMap));
}
@Override
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
int id = getId();
if (id == NO_ID) return;
Parcelable superState = super.onSaveInstanceState();
IsolatedLayoutSaveState iss = new IsolatedLayoutSaveState(superState);
SparseArray<Parcelable> array = iss.childStates;
super.dispatchSaveInstanceState(array);
container.put(id, iss);
}
private void processTopNode(SparseArray<TopBottomNodeInfo> lastTopNodeList, SparseArray<TopBottomNodeInfo> newTopArr, SparseArray<TopBottomNodeInfo> newEndingArr, RecyclerView.LayoutManager layoutManager, int first, int last) {
for (int i = 0; i < topNodeList.size(); i++) {
int pos = topNodeList.keyAt(i);
ShieldDisplayNode node = topNodeList.valueAt(i);
if (node == null) {
continue;
}
InnerTopInfo innerTopInfo = node.innerTopInfo;
if (innerTopInfo == null) {
continue;
}
int line = innerTopInfo.offset;
int startTop = getTopOrBottomPosition(TOP, layoutManager, innerTopInfo.startPos, first, last);
int endBottom = getTopOrBottomPosition(BOTTOM, layoutManager, innerTopInfo.endPos, first, last);
invalidateView(pos, node);
TopBottomNodeInfo info = getTopNodeInfo(pos, node, line, endBottom);
if (isTop(line, startTop, endBottom, node)) {
if (isEnding(line, endBottom, info.height)) {
if (info.state != TopState.ENDING) {
info.state = TopState.ENDING;
newEndingArr.put(pos, info);
}
} else {
if (info.state != TopState.TOP) {
info.state = TopState.TOP;
newTopArr.put(pos, info);
}
}
currentTopNodeList.put(pos, info);
lastTopNodeList.remove(pos);
}
}
}
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id) {
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); //稀疏数组 的Viewholder 取代HashMap 这里是复用
if (viewHolder == null) {
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id); //在当前view里面查找这个 id 这里也是复用
if (childView == null) {
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
/**
* 这里添加所需要的布局id map
*
* @return
*/
@Override
protected SparseArray<Integer> getLayoutIdMap() {
SparseArray<Integer> sparseArray = new SparseArray<>();
// 每个view类型都是一样的布局,只是在需要的时候通过view_stub加载成自己的布局view
sparseArray.put(Constant.MSG_TYPE_SHARE_MESSAGE_TEXT, R.layout.share_fragment_item_main_layout);
sparseArray.put(Constant.MSG_TYPE_SHARE_MESSAGE_LINK, R.layout.share_fragment_item_main_layout);
sparseArray.put(Constant.MSG_TYPE_SHARE_MESSAGE_VIDEO, R.layout.share_fragment_item_main_layout);
sparseArray.put(Constant.MSG_TYPE_SHARE_MESSAGE_IMAGE, R.layout.share_fragment_item_main_layout);
return sparseArray;
}
private static SparseArray<Map<TrackGroupArray, SelectionOverride>> cloneSelectionOverrides(
SparseArray<Map<TrackGroupArray, SelectionOverride>> selectionOverrides) {
SparseArray<Map<TrackGroupArray, SelectionOverride>> clone = new SparseArray<>();
for (int i = 0; i < selectionOverrides.size(); i++) {
clone.put(selectionOverrides.keyAt(i), new HashMap<>(selectionOverrides.valueAt(i)));
}
return clone;
}
private void storeView(int parentId, int id, View viewRetrieve) {
SparseArray<View> sparseArrayViewsParent = mSparseSparseArrayView.get(parentId);
if (sparseArrayViewsParent == null) {
sparseArrayViewsParent = new SparseArray<>();
mSparseSparseArrayView.put(parentId, sparseArrayViewsParent);
}
sparseArrayViewsParent.put(id, viewRetrieve);
}
/**
* Test sending UAI to an app whose session id is the same as a removed app
* but is indeed the SAME app
*
* @see SdlRouterService#sendPacketToRegisteredApp(SdlPacket)
*/
public void testRegisterAppExistingSessionIDSameApp() {
if (Looper.myLooper() == null) {
Looper.prepare();
}
Method method;
try {
// create instance of router service
SdlRouterService sdlRouterService = new SdlRouterService();
// We need a registered app for this to work
Message message = Message.obtain();
SdlRouterService.RegisteredApp app1 = sdlRouterService.new RegisteredApp("12345",message.replyTo);
SdlRouterService.RegisteredApp app2 = sdlRouterService.new RegisteredApp("12344",message.replyTo);
HashMap<String,SdlRouterService.RegisteredApp> registeredApps = new HashMap<>();
registeredApps.put(app1.getAppId(),app1);
registeredApps.put(app2.getAppId(),app2);
// set registered apps array
Field raf = sdlRouterService.getClass().getDeclaredField("registeredApps");
raf.setAccessible(true);
raf.set(sdlRouterService, registeredApps);
// need a session map too
SparseArray<String> sessionMap = new SparseArray<String>();
sessionMap.put(1, "12345");
Field sessionMapField = sdlRouterService.getClass().getDeclaredField("bluetoothSessionMap");
sessionMapField.setAccessible(true);
sessionMapField.set(sdlRouterService, sessionMap);
// set cleaned session map
SparseIntArray testCleanedMap = new SparseIntArray();
testCleanedMap.put(1, 12345);
Field f = sdlRouterService.getClass().getDeclaredField("cleanedSessionMap");
f.setAccessible(true);
f.set(sdlRouterService, testCleanedMap);
// set session hash id map
SparseIntArray testHashIdMap = new SparseIntArray();
testHashIdMap.put(1, 12345);
Field f2 = sdlRouterService.getClass().getDeclaredField("sessionHashIdMap");
f2.setAccessible(true);
f2.set(sdlRouterService, testHashIdMap);
// make sure maps are set and NOT the same
Assert.assertNotNull(raf.get(sdlRouterService));
Assert.assertNotNull(sessionMapField.get(sdlRouterService));
Assert.assertNotNull(f.get(sdlRouterService));
Assert.assertNotNull(f2.get(sdlRouterService));
// make da RPC
UnregisterAppInterface request = new UnregisterAppInterface();
request.setCorrelationID(SAMPLE_RPC_CORRELATION_ID);
// build protocol message
byte[] msgBytes = JsonRPCMarshaller.marshall(request, (byte) version);
pm = new ProtocolMessage();
pm.setData(msgBytes);
pm.setSessionID((byte) sessionId);
pm.setMessageType(MessageType.RPC);
pm.setSessionType(SessionType.RPC);
pm.setFunctionID(FunctionID.getFunctionId(request.getFunctionName()));
pm.setCorrID(request.getCorrelationID());
if (request.getBulkData() != null) {
pm.setBulkData(request.getBulkData());
}
// binary frame header
byte[] data = new byte[12 + pm.getJsonSize()];
binFrameHeader = SdlPacketFactory.createBinaryFrameHeader(pm.getRPCType(), pm.getFunctionID(), pm.getCorrID(), pm.getJsonSize());
System.arraycopy(binFrameHeader.assembleHeaderBytes(), 0, data, 0, 12);
System.arraycopy(pm.getData(), 0, data, 12, pm.getJsonSize());
// create packet and invoke sendPacketToRegisteredApp
SdlPacket packet = new SdlPacket(4, false, SdlPacket.FRAME_TYPE_SINGLE, SdlPacket.SERVICE_TYPE_RPC, 0, sessionId, data.length, 123, data);
packet.setTransportRecord(new TransportRecord(TransportType.BLUETOOTH,null));
method = sdlRouterService.getClass().getDeclaredMethod("sendPacketToRegisteredApp", SdlPacket.class);
Boolean success = (Boolean) method.invoke(sdlRouterService, packet);
// Since it is the same app, allow the packet to be sent
Assert.assertTrue(success);
} catch (Exception e) {
Assert.fail("Exception in sendPacketToRegisteredApp, " + e);
}
}
@Override
public void onParseBindAdapterElements(List<BindAdapterElement> list) {
if (list == null || list.size() == 0)
return;
final Context context = this.mWeakContext.get();
final SparseArray<Array<DataBindParser.ItemBindInfo>> mItemBinds = this.mItemBinds;
final SparseArray<DataBindParser.AdapterInfo> mReferMap = this.mOtherInfoMap;
List<ItemElement> ies;
Array<DataBindParser.ItemBindInfo> infos;
DataBindParser.ItemBindInfo info;
boolean oneItem;
int adapterViewId;
int selectMode;
for (BindAdapterElement bae : list) {
ies = bae.getItemElements();
if (ies == null || ies.size() == 0)
continue;
infos = new Array<>(3);
oneItem = ies.size() == 1;
adapterViewId = ResourceUtil.getResId(context, bae.getId(), ResourceUtil.ResourceType.Id);
try {
selectMode = Integer.parseInt(bae.getSelectMode());
if (selectMode != ISelectable.SELECT_MODE_SINGLE && selectMode != ISelectable.SELECT_MODE_MULTI) {
throw new DataBindException("the value of selectMode can only be ISelectable.SELECT_MODE_SINGLE" +
" or ISelectable.SELECT_MODE_MULTI , please check the value of selectMode " +
"in <bindAdapter> element");
}
} catch (NumberFormatException e) {
throw new DataBindException("the value of selectMode can only be ISelectable.SELECT_MODE_SINGLE" +
" or ISelectable.SELECT_MODE_MULTI , please check the value of selectMode " +
"in <bindAdapter> element");
}
mReferMap.put(adapterViewId, new DataBindParser.AdapterInfo(bae.getReferVariable(),
bae.getTotalRefers(), selectMode));
mItemBinds.put(adapterViewId, infos);
for (ItemElement ie : ies) {
info = new DataBindParser.ItemBindInfo();
info.layoutId = ResourceUtil.getResId(context, ie.getLayoutName(), ResourceUtil.ResourceType.Layout);
//in multi item ,index must be declared
if (!oneItem)
info.tag = Integer.parseInt(ie.getTag().trim());
info.itemEvents = parseListItemEventPropertyInfos(ie.getPropertyElements());
info.itemBinds = parseListItemBindInfos(context, ie.getBindElements());
infos.add(info);
}
}
}