1 /*
2  * Copyright (C) 2016 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 com.android.settings.dashboard;
18 
19 import android.content.res.Resources;
20 import android.view.View;
21 
22 import org.hamcrest.Description;
23 import org.hamcrest.Matcher;
24 import org.hamcrest.TypeSafeMatcher;
25 
26 /***
27  * Matches on the first view with id if there are multiple views using the same Id.
28  */
29 public class FirstIdViewMatcher {
30 
withFirstId(final int id)31     public static Matcher<View> withFirstId(final int id) {
32         return new TypeSafeMatcher<View>() {
33             Resources resources = null;
34             private boolean mMatched;
35 
36             public void describeTo(Description description) {
37                 String idDescription = Integer.toString(id);
38                 if (resources != null) {
39                     try {
40                         idDescription = resources.getResourceName(id);
41                     } catch (Resources.NotFoundException e) {
42                         // No big deal, will just use the int value.
43                         idDescription = String.format("%s (resource name not found)", id);
44                     }
45                 }
46                 description.appendText("with first id: " + idDescription);
47             }
48 
49             public boolean matchesSafely(View view) {
50                 this.resources = view.getResources();
51                 if (mMatched) {
52                     return false;
53                 } else {
54                     mMatched = id == view.getId();
55                     return mMatched;
56                 }
57             }
58         };
59     }
60 }
61