1 /*
2  * Copyright (C) 2019 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 
17 package android.view.accessibility;
18 
19 import android.view.View;
20 
21 /** @hide */
22 public final class AccessibilityNodeIdManager {
23     private WeakSparseArray<View> mIdsToViews = new WeakSparseArray<View>();
24     private static AccessibilityNodeIdManager sIdManager;
25 
26     /**
27      * Gets singleton.
28      * @return The instance.
29      */
getInstance()30     public static synchronized AccessibilityNodeIdManager getInstance() {
31         if (sIdManager == null) {
32             sIdManager = new AccessibilityNodeIdManager();
33         }
34         return sIdManager;
35     }
36 
AccessibilityNodeIdManager()37     private AccessibilityNodeIdManager() {
38     }
39 
40     /**
41      * Register view to be kept track of by the accessibility system.
42      * Must be paired with unregisterView, otherwise this will leak.
43      * @param view The view to be registered.
44      * @param id The accessibilityViewId of the view.
45      */
registerViewWithId(View view, int id)46     public void registerViewWithId(View view, int id) {
47         synchronized (mIdsToViews) {
48             mIdsToViews.append(id, view);
49         }
50     }
51 
52     /**
53      * Unregister view, accessibility won't keep track of this view after this call.
54      * @param id The id returned from registerView when the view as first associated.
55      */
unregisterViewWithId(int id)56     public void unregisterViewWithId(int id) {
57         synchronized (mIdsToViews) {
58             mIdsToViews.remove(id);
59         }
60     }
61 
62     /**
63      * Accessibility uses this to find the view in the hierarchy.
64      * @param id The accessibility view id.
65      * @return The view.
66      */
findView(int id)67     public View findView(int id) {
68         View view = null;
69         synchronized (mIdsToViews) {
70             view = mIdsToViews.get(id);
71         }
72         return view != null && view.includeForAccessibility() ? view : null;
73     }
74 }
75